- es6规定了迭代协议,它不是新的内置对象或者什么语法,仅仅是个协议
- 要想成为可迭代对象,它或者它的原型上必须有
Symbol.iterator,访问该属性返回一个函数,该函数的next()方法返回`{ value: '', next: false }
class CreateIteractor {
constructor(data) {
this.data = data
}
[Symbol.iterator]() {
let index = 0
return {
next: () => {
if (index < this.data.length) {
return { value: this.data[index++], done: false }
} else {
return { done: true }
}
}
}
}
}
const iteractor = new CreateIteractor(['as', 'tf', 'oo'])
for (let i of iteractor) {
console.log(i)
}
- 迭代对象使用
for...of循环
-
String Array TypedArray Map Set都是可迭代对象
- 需要可迭代对象的语法
for...of
- 展开语法在数组中或者函数的参数中使用