function * generator(k){ console.log(‘begin‘); var x = yield k; console.log(‘x:‘,x); var y = yield x+k; console.log(‘y:‘,y); return x+y+k; } var o = generator(1); var r = o.next(); console.log(‘1:‘+r.value, ‘done:‘+r.done); r = o.next(3); console.log(‘2:‘+r.value,‘done:‘+r.done); r = o.next(5); console.log(‘3:‘+r.value,‘done:‘+r.done); //log begin 1:1 done:false x: 3 2:4 done:false y: 5 3:9 done:true =========================================================================== function * generator(k){ console.log(‘begin‘); var x = yield k; console.log(‘x:‘,x); return ‘end‘; var y = yield x+k; console.log(‘y:‘,y); return x+y+k; } var o = generator(1); var r = o.next(); console.log(‘1:‘+r.value,‘done:‘+r.done); r = o.next(3); console.log(‘2:‘+r.value,‘done:‘+r.done); r = o.next(5); console.log(‘3:‘+r.value,‘done:‘+r.done); //log begin 1:1 done:false x: 3 2:end done:true 3:undefined done:true
迭代构造器可以接受初值,在构造时传入而非首次调用 next 时,
yield 后面的值被返回,后继代码暂时中断,直到调用 next 方法,
yield 赋值表达式:在下一次调用 next 时将传入的值赋給变量,
如果遇到 return 则迭代执行结束
时间: 2024-10-17 13:53:52