文章目录
Generator 函数是 ES6 提供的一种 异步编程解决方案
(Generator 函数是一个状态机,封装了多个内部状态)
Generator 函数就是遍历器生成函数
function* 名称
体内 yield 表达式(状态等待执行 并返回)
一、next()方法
1.next不带参
function* fun(){
yield 1+1;
yield 2+2;
yield 3+3;
yield 4+4;
return 10; //替换最终的value:undefined
}
//执行该函数
let f=fun(); //执行之后返回遍历器
console.log(f.next()); //{value: 2, done: false}
console.log(f.next()); //{value: 4, done: false}
console.log(f.next()); //{value: 6, done: false}
console.log(f.next()); //{value: 8, done: false}
console.log(f.next()); //{value: 10, done: true}
//不加return,value:undefined
2.next带参
参数指的是上一次yeild表达式的返回值 (本身是undefined)
//next遍历带参 参数指的是上一次yeild表达式的返回值(本身是undefined)
function* method(){
let x=yield 1+2;
console.log(x);
let y=yield 3+x;
console.log(y);
return y+10;
}
let met=method();
console.log(met.next()); //{value: 3, done: false}
console.log(met.next(3)); //3 {value: 6, done: false}
console.log(met.next(8)); //8 {value: 18, done: true}
3.面试题
(1)yield表达式如果用在另一个表达式之中,必须放在圆括号里面
function* fun(){
let x=yield 5+(yield 1+2);
return x;
}
let xf=fun();
console.log(xf.next()); //{value: 3, done: false}
console.log(xf.next()); //{value: NaN, done: false} (5+undefined)
console.log