1. generator传参和next传参
genTest(); function genTest(){ let g = gen(0); //0为普通函数参数 console.log('next: ', g.next(10)); //第一个next执行第一个yield之前的代码,10不被采用,无效 console.log('next: ', g.next(20)); //第二个next执行第二个yield之前,第一个yield之后的代码,20被赋值给第一个yield等号左侧的a,所以a等于20 console.log('next: ', g.next(30)); //next传入的值只对yield左侧的值有影响,对yield的右侧值,及返回值无影响 console.log('next: ', g.next(40)); //next不传值,则yield左侧的值为undefined } function* gen(p){ console.log('1',p); var a = yield 100; console.log('a', a); var b = yield 200; console.log('b', b); var c = yield 300; console.log('c',c); }
输出
1 0 next: {value: 100, done: false} //不受next传入值影响 a 20 next: {value: 200, done: false} b 30 next: {value: 300, done: false} c 40 next: {value: undefined, done: true}
2. generator经典实例
// 斐波那契竖列生成器 function* fib() { let [x, y] = [0, 1]; while (true) { yield x; [x, y] = [y, x + y]; } } // 阶乘 function* factorial() { let n = 1; let fac = 1; while (true) { yield fac; fac = fac * ++n; } }