为什么map, foreach, andreduce不使用迭代器函数 on Symbol.iterator?
class MyArray extends Array {
*[Symbol.iterator]() {
for(let x = 0; x < this.length; x++) { yield this[x]*2 }
}
}
const log = console.log
const arr = new MyArray(1,2,3)
console.log([...arr]) // [2,4,6]
log(arr.map((i) => i)) // [1,2,3]Run Code Online (Sandbox Code Playgroud)
和:
const arr = [1,2,3]
Object.defineProperty(Object.getPrototypeOf(arr), Symbol.iterator, {
value: function*() {
for(let x = 0; x < this.length; x++) { yield this[x]*2 }
}
})
const log = console.log
log([...arr]) // [2,4,6]
log(arr.map((i) => i)) // [1,2,3]Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |