ES6中的迭代器(Iterator)和生成器(Generator)及关键字yield

 

迭代器(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
*/

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值