一、什么是迭代器
ES6约定,任何数据结构只要具备Symbol.iterator属性(这个属性就是Iterator的具体实现,它本质上是当前数据结构默认的迭代器生成函数),就可以被遍历——准确地说,是被for...of...循环和迭代器的next方法遍历。 事实上,for...of...的背后正是对next方法的反复调用。
以数组为例:
const arr = [1, 2, 3]
const len = arr.length
for(item of arr) {
console.log(item) // 1 2 3
}
const arr = [1, 2, 3]
// 通过调用iterator,拿到迭代器对象
const iterator = arr[Symbol.iterator]()
// 对迭代器对象执行next,就能逐个访问集合的成员
console.log(iterator.next()) // { value: 1, done: false }
console.log(iterator.next()) // { value: 2, done: false }
console.log(iterator.next()) // { value: 3, done: false }
console.log(iterator.next()) // { value: undefined, done: true }
什么是可迭代对象呢?
迭代器和可迭代对象是两个不同的概念,上面例子中arr是一个可迭代对象,iterator是一个迭代器。
当一个对象实现了iterable protocol协议时,它就是一个可迭代对象。
可迭代对象的要求:
是必须实现 @@iterator (这是规范的名字) 方法,在代码中我们使用 [Symbol.iterator] (这是实际用的名字)访问该属性;
这个[Symbol.iterator] 方法需要返回一个迭代器;
二、ES6实现迭代器
// ES6编写一个迭代器生成函数
// function *iteratorGenerator() {
// yield '1号选手'
// yield '2号选手'
// yield '3号选手'
// }
function* iteratorGenerator() {
yield* ['1号选手', '2号选手', '3号选手']
}
// 测试用例
const iterator = iteratorGenerator()
console.log(iterator.next()) // { value: '1号选手', done: false }
console.log(iterator.next()) // { value: '2号选手', done: false }
console.log(iterator.next()) // { value: '3号选手', done: false }
console.log(iterator.next()) // { value: undefined, done: true }
三、ES5实现迭代器
function iteratorGenerator(list) {
var idx = 0
var len = list.length
return {
next: function() {
var done = idx >= len
var value = !done ? list[idx++] : undefined
return {
value: value,
done: done
}
}
}
}
// 测试用例
var iterator = iteratorGenerator(['1号选手', '2号选手', '3号选手'])
console.log(iterator.next()) // { value: '1号选手', done: false }
console.log(iterator.next()) // { value: '2号选手', done: false }
console.log(iterator.next()) // { value: '3号选手', done: false }
console.log(iterator.next()) // { value: undefined, done: true }
四、将一个对象转换为可迭代对象
const info = {
friends: ["aaa", "bbb", "ccc"],
[Symbol.iterator] () {
let index = 0
const infoIterator = {
// 将next方法改为箭头函数, 这样next方法中就不在绑定this, this回去上层作用域中寻找, 上层作用域中的this会指向info
next: () => {
if (index < this.friends.length) {
return { done: false, value: this.friends[index++] }
} else {
return { done: true }
}
}
}
return infoIterator
}
}
// 例如上面的info对象本来是没办法for...of操作的, 变成可迭代对象后就可以进行for...of操作
for (item of info) {
console.log(item) // aaa bbb ccc
}
五、参考链接