JavaScript 迭代器
JavaScript 迭代器 是一个对象或者模式,它允许我们遍历列表或者集合。迭代器定义了序列并且通过实现迭代器协议返回一个对象,该对象包含一个 next() 方法 ,该方法包含值和是否已完成的信息。值包含迭代器序列的下一个值,而 done 是布尔值 true 或者 false,如果序列的最后一个值已经被消耗掉则为 true,否则为 false。
我们可以检查一个实体是否默认可迭代。我们可以检查它的原型,并查看是否具有一个Symbol(Symbol.iterator) 方法。
在 Array.prototype 中,你会发现 Symbol(Symbol.iterator): ƒ values() 方法 。数组默认是可迭代的。同时,String、Map 和 Set 是内置的可迭代对象,因为它们的原型对象都有一个 Symbol.iterator() 方法 。
示例: 这个示例使用 symbol.iterator 方法来遍历数组。
<script>
const array = ['a', 'b', 'c'];
const it = array[Symbol.iterator]();
// and on this iterator method we have ‘next’ method
console.log(JSON.stringify(it.next()));
//{ value: "a", done: false }
console.log(JSON.stringify(it.next()));
//{ value: "b", done: false }
console.log(JSON.stringify(it.next()));
//{ value: "c", done: false }
console.log(JSON.stringify(it.next()));
/* Actual it.next() will be { value: undefined,
done: true } but here you will get
{done: true} output because of JSON.stringify
as it omits undefined values*/
</script>
输出结果:
{"value":"a","done":false}
{"value":"b","done":false}
{"value":"c","done":false}
{"done":true}
使用 for.of循环 ,我们可以遍历任何遵循可迭代协议的实体(例如:对象)。每次调用 next()方法 时, for.of循环 都会取出返回的值。
示例: 这个示例使用for…of循环来遍历数组。
<script>
const array = ['a', 'b', 'c'];
const it = array[Symbol.iterator]()
for (let value of it) {console.log(value)}
</script>
输出:
a
b
c
Iterable协议: 对象必须定义一个具有’Symbol.iterator’键的方法,该方法返回一个自身遵循iterator协议的对象。对象必须定义一个返回具有两个属性’value’和’done’的对象的’next’方法。
语法:
{value: 'item value', done: boolean}
错误场景:
var newIt = arr[Symbol.iterator]
newIt()
//Because it does not properly bind
Uncaught TypeError: Cannot convert undefined or null to object
//How we can fix this
//var newIt = arr[Symbol.iterator].bind(arr);
newIt()
Array Iterator { }
创建我们自己的可迭代对象:
<script>
var iterable = {
i: 0,
[Symbol.iterator]() {
var that = this;
return {
next() {
if (that.i < 5) {
return { value: that.i++, done: false }
} else {
return { value: undefined, done: true }
}
}
}
}
}
for(let value of iterable){console.log(value)}
</script>
输出:
0
1
2
3
4