let a = ['a', 'b', 'c']
// eg.1:for写法
console.log('for a[symbol.iterator]')
for (let ret, it = a[Symbol.iterator](); (ret = it.next()) && !ret.done;) {
console.log(ret.value)
}
// eg.2:while写法
let ret
let it = a[Symbol.iterator]()
console.log('while a it')
while ((ret = it.next()) && !ret.done) {
console.log(ret.value)
}
// eg.3:直接for-of,内部实际是eg.1的运行方法。
console.log('for of a')
for (let i of a) {
console.log(i)
}
// 自定义迭代器
// 斐波那契序列
// 1 1 2 3 5 8 13
let Fib = {
[Symbol.iterator] () {
let n1 = 1; // 闭包
let n2 = 1;
return {
[Symbol.iterator] () {
return this
},
next () {
let current = n2
n2 = n1
n1 = n1 + current
return { value: current, done: false }
},
return (v) {
console.log('done')
return { value: v, done: true }
}
}
}
}
console.log('for of Fib')
for (let i of Fib) { // 参照eg.3/eg.1:去理解这里的执行。
if (i > 50) break
console.log(i)
}
js-迭代器及for-of
最新推荐文章于 2023-12-01 13:14:23 发布