迭代器协议
-
迭代器协议定义了产生一系列值的一个标准方式,迭起协议规定需要返回一个带 next() 方法的对象。 next() 可以被多次执行,每次执行都会返回一个对象,该对象包含两个属性,done 和 value:
- done 是一个 boolean,在没有迭代完时返回 false,迭代完成后返回 true;
- value 就是被迭代的返回值,当 done 为 true 时可以省略;
-
实现了以上两点才会满足一个迭代器协议;
迭代器
const obj = {
store: ['foo', 'bar', 'baz'],
[Symbol.iterator]: function () {
let index = 0
return {
next: () => {
const result = {
value: this.store[index],
done: index++ >= this.store.length
}
return result
}
}
}
}
// 实现了 iterator 迭代器协议,则可以使用 for...of 遍历
for (const item of obj) {
console.log('循环体', item)
}
// 循环体 foo
// 循环体 bar
// 循环体 baz
ES6+ for…of
上一篇