上海网站建设商城,做设计的公司的网站,常州网站制作套餐,公司官方网站制作在JavaScript中#xff0c;迭代器是一种允许我们遍历集合中元素的对象。迭代器对象具有一个next()方法#xff0c;该方法返回value和done。value是当前迭代的值#xff0c;done属性是一个布尔值#xff0c;表示是否到达了集合的末尾。 迭代器协议
一个迭代器对象必须具备以… 在JavaScript中迭代器是一种允许我们遍历集合中元素的对象。迭代器对象具有一个next()方法该方法返回value和done。value是当前迭代的值done属性是一个布尔值表示是否到达了集合的末尾。 迭代器协议
一个迭代器对象必须具备以下特性
next()方法每次调用返回一个对象其结构为{value:...,done:...}。如果迭代完成value可能是任意值done则为true。可选的return()方法允许提前终止迭代其可选地返回一个值。可选的throw()方法允许在迭代过程中抛出错误。
创建迭代器
使用Symbol.iterator来实现迭代器。
const myArray [a, b, c]
const myIterator {data: myArray,index: 0,[Symbol.iterator] () {return this},next () {if (this.index this.data.length) {return { value: this.data[this.index], done: false }} else {return { done: true }}}
}for (let item of myIterator) {console.log( ~ item:, item)
}生成器函数
生成器函数是实现迭代器的一种更简便的方式。生成器函数使用function*语法定义并且可以使用yield关键字来产生一系列值。当生成器函数被调用时它返回一个迭代器对象该对象可以使用next()方法来迭代。
function* numberGenerator(max) {for (let i 0; i max; i) {yield i}
}const gen numberGenerator(5)console.log(gen.next()) // { value: 0, done: false }
console.log(gen.next()) // { value: 1, done: false }
console.log(gen.next()) // { value: 2, done: false }
console.log(gen.next()) // { value: 3, done: false }
console.log(gen.next()) // { value: 4, done: false }
console.log(gen.next()) // { value: undefined, done: true }