es6 的 generator 还是有点迷惑

2015-05-04 11:31:53 +08:00
 coolicer
function *foo(x) {
/*1*/    var y = 2 * (yield (x + 1));
/*2*/    var z = yield (y / 3);
/*3*/    return (x + y + z);
}

var it = foo( 5 );

// note: not sending anything into `next()` here
console.log( it.next() );       // { value:6, done:false }
console.log( it.next( 12 ) );   // { value:8, done:false }
console.log( it.next( 13 ) );   // { value:42, done:true }

第一次next(),{ value:6, done:false }
第二次next(12),我以为函数应该执行到2那里,然后 var y = 2 * 6
....
看来我是没有明白,求打醒。

如果把yeild看成是可以接收send的数据,好像又可以走通了。

2947 次点击
所在节点    Node.js
3 条回复
yangff
2015-05-04 11:38:23 +08:00
x = 5
y = 2 * 12 // => 24
y / 3 // => 8
z = 13
x + y + z = 5 + 24 + 13 // => 42?
coolicer
2015-05-04 11:40:04 +08:00
@yangff 是这样的。
coolicer
2015-05-04 11:56:37 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/188286

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX