ES6之genorator和yield使用(迭代器)

例1:

function *g(){
    yield 100
    yield 200
    return 300
}
let res = g()
console.log(res);
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
// 输出:
/*
Object [Generator] {}
{ value: 100, done: false }
{ value: 200, done: false }
{ value: 300, done: true }
{ value: undefined, done: true }
*/

next方法类似promise .then链式调用
done属性的值代表是否调用完毕

例2:

function* g() {
  yield 100;
  yield 200;
  yield g2();
  return 500;
}

function* g2() {
  yield 300;
  yield 400;
}

let res = g();
console.log(res);
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
// 输出
/*
Object [Generator] {}
{ value: 100, done: false }
{ value: 200, done: false }
{ value: Object [Generator] {}, done: false }
{ value: 500, done: true }
{ value: undefined, done: true }
*/

可以看出,正常情况下,如果在一个迭代器里调用另一个迭代器,返回的是迭代器本身,不会对另一个迭代器遍历
如果想要调用另一个迭代器进行遍历的话,可以使用 yeild* 修饰这个迭代器:

function* g() {
  yield 100;
  yield 200;
  yield* g2();
  return 500;
}

function* g2() {
  yield 300;
  yield 400;
}

let res = g();
console.log(res);
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
console.log(res.next());
// 输出:
/*
Object [Generator] {}
{ value: 100, done: false }
{ value: 200, done: false }
{ value: 300, done: false }
{ value: 400, done: false }
{ value: 500, done: true }
{ value: undefined, done: true }
*/
posted @ 2021-03-09 11:18  zoo-x  阅读(93)  评论(0编辑  收藏  举报