# 迭代器
工作原理 :
- 创建一个指针对象,指向当前数据结构的起始地址
- 第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员
- 接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员
- 每调用 next 方法返回一个包含 value 和 done 属性的对象
** 注意 : ** 需要自定义遍历数据的时候,要想到迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const banji = { name: '超级一班', stus: [ 'xiaoming', 'xiaolin', 'xiaotian', 'knight' ], [Symbol.iterator]() { let index = 0 return { next: () => { if (index < this.stus.length) { const result = {value: this.stus[index], done: false} index++ return result } else return {value: undefined, done: true} } } } }
for (name of banji) { console.log(name) }
|