JavaScript 生成器 yield next方法

生成器

什么是生成器

image-20220221101156921

yield的返回值

image-20220221113324459

  1. yield后面的返回值,返回到调用next()返回的对象的value里面

生成器.return()代码提前终止执行

image-20220221114103864

  1. return()实现代码的提前终止执行

生成器代替迭代器

生成器代替迭代器-方式一

03_生成器代替迭代器.js

关键代码

image-20220221161411043

对比

image-20220221161930922

function makeIterator(array) {
  let nextIndex = 0;
  return {
    next: function () {
      return nextIndex < array.length
        ? { value: array[nextIndex++], done: false }
        : { value: undefined, done: true };
    },
  };
}

const it = makeIterator(['a', 'b']);

console.log(it.next()); //=> { value: 'a', done: false }
console.log(it.next()); //=> { value: 'b', done: false }
console.log(it.next()); //=> { value: undefined, done: true }
console.log('------------------------------------------------');
// ----------------------------------------------------

function* makeGenerator(array) {
  for (const item of array) {
    yield item;
  }
}

const gt = makeGenerator(['a', 'b']);

console.log(gt.next()); //=> { value: 'a', done: false }
console.log(gt.next()); //=> { value: 'b', done: false }
console.log(gt.next()); //=> { value: undefined, done: true }

生成器代替迭代器-方式二

04_生成器代替迭代器_方式二.js

function* makeGenerator(array) {
  yield* array;
}

const gt = makeGenerator(['a', 'b']);

console.log(gt.next()); //=> { value: 'a', done: false }
console.log(gt.next()); //=> { value: 'b', done: false }
console.log(gt.next()); //=> { value: undefined, done: true }

总结

image-20220221162448044

  1. 三种写法
    1. 自己手动操作,一步一步计算,不推荐
    2. 使用for…of…循环遍历,推荐
    3. 语法糖形式,推荐

类中使用生成器代替迭代器

代码对比

image-20220225105331872

关键代码

image-20220225105035075

class Classroom {
  constructor(address, name, students) {
    this.address = address;
    this.name = name;
    this.students = students;
  }

  *[Symbol.iterator]() {
    yield* this.students;
  }
}

const c1 = new Classroom('Beijing', 'Xuexi', ['Alice', 'Bruce', 'Celina']);
const iterator = c1[Symbol.iterator]();
console.log(iterator.next()); //=> { done: false, value: 'Alice' }
console.log(iterator.next()); //=> { done: false, value: 'Bruce' }
console.log(iterator.next()); //=> { done: false, value: 'Celina' }
console.log(iterator.next()); //=> { done: true, value: undefined }

console.log('------------------');
for (let item of c1) {
  console.log(item);
  //=> Alice
  //=> Bruce
  //=> Celina
}

生成器函数的自动执行

image-20220225105924680

  1. 采用的是递归调用的思路

image-20220225110011999

  1. 采用第三方co包,可以模拟上面的代码
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值