[英]Es6 generators: i += yield i;
So this code was published on same places before as an example of generators in es6: 因此,此代码之前作为es6中的生成器示例发布在相同位置:
function *addGenerator() {
var i = 0;
while (true) {
i += yield i;
}
}
var gen = addGenerator();
console.log(gen.next().value);
console.log(gen.next(3).value);
console.log(gen.next(5).value);
Which gives: 0, 3, 8
. 给出:
0, 3, 8
。
What I don't get is why this += yield i
works. 我没有得到的是为什么这
+= yield i
工作。 I guess it's because we wait until we get the next value, and if you pass something in next()
it's an implicit return. 我想这是因为我们等到我们得到下一个值,如果你在
next()
传递一些东西,它就是一个隐含的返回。 So far so good. 到现在为止还挺好。 But why is the name of the var
i
? 但为什么var
i
的名字?
If I do: 如果我做:
function *addGenerator() {
var i = 0;
var j = 0;
while (true) {
i += yield j;
}
}
It does not work, so there is something special about that var... Who knows? 它不起作用,所以这个变量有一些特别之处...谁知道呢?
In second example you'll get 0 0 0
as an output, because gen.next().value
is the value of j
variable - and this is 0 - you don't assign to it in a loop. 在第二个例子中,你将获得
0 0 0
作为输出,因为gen.next().value
是j
变量的值 - 这是0 - 你不在循环中分配它。
General form of yield
keyword can be seen as something like: yield
关键字的一般形式可以看作是:
var passedToNext = yield returnThisAsNext_value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.