码迷,mamicode.com
首页 > 其他好文 > 详细

ecma6 yield

时间:2015-07-24 06:49:07      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

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 则迭代执行结束

 

ecma6 yield

标签:

原文地址:http://www.cnblogs.com/ecalf/p/4672296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!