遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。
1 2 3 4 5
| let arr = ['hello', 'world']; let map = arr[Symbol.iterator](); console.log(map.next()); console.log(map.next()); console.log(map.next());
|
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 27 28 29
| { let obj = { start: [1, 3, 2], end: [7, 9, 8], [Symbol.iterator]() { let selt = this; let index = 0; let arr = selt.start.concat(selt.end); return { next() { if (index < arr.length) { return { value: arr[index++], done: false } } else { return { value: arr[index++], done: true } } } } } } for (let key of obj) { console.log(key); }
|