迭代器(Iterator):
迭代器是一种特殊对象,它具有一些专门为迭代过程设计的专有接口,所有的迭代器对象都有一个next()方法,每次调用都返回一个结果对象。结果对象有两个属性:一个是value,表示下一个将要返回的值;另一个是done,它是一个布尔类型的值,当没有更多可返回数据时返回true。迭代器还会保存一个内部指针,用来指向当前集合中值的位置,每调用一次next()方法,都会返回下一个可用的值。如果在最后一个值返回后再调用next()方法,那么返回的对象中属性done的值为true,属性value若未定义,则为undefined。
const arr = ['blue', 'green', 'red'];
function creatIterator(arr) {
let nextIndex = 0;
return {
// 注意:返回值是包裹'next'函数的对象
next() {
if (nextIndex < arr.length) {
return {
// 注意'nextIndex++'自增
value: arr[nextIndex++],
done: false
}
} else {
return {
// value: 'no next', // 若使用'value',超过数组长度均打印指定值
done: true
}
}
}
}
}
// 传参
const item = creatIterator(arr);
// 调用迭代器
console.log('第一次调用:' + item.next().value);
console.log('第二次调用:' + item.next().value);
console.log('第三次调用:' + item.next().value);
console.log('第四次调用:' + item.next().value);
console.log('第五次调用:' + item.next().done);
/* 打印结果:
第一次调用:blue
第二次调用:green
第三次调用:red
第四次调用:undefined
第五次调用:true
*/
生成器(Generator):
生成器是一种返回迭代器的函数,通过function关键字后的星号(*)来表示,函数中会用到新的关键字yield(必须在生成器内部使用)。星号可以紧挨着function关键字,也可以在中间添加一个空格。
const arr = ['blue', 'green', 'red'];
function *creatIterator(arr) {
for (let i = 0; i < arr.length; i++) {
// 表示每次调用都返回arr[i]的值,与return类似
yield arr[i];
}
}
const item = creatIterator(arr);
console.log('第一次调用:' + item.next().value);
console.log('第二次调用:' + item.next().value);
console.log('第三次调用:' + item.next().value);
console.log('第四次调用:' + item.next().value);
console.log('第五次调用:' + item.next().done);
/* 打印结果:
第一次调用:blue
第二次调用:green
第三次调用:red
第四次调用:undefined
第五次调用:true
*/