此生成器如何返回3?

问题描述 投票:-1回答:1

虽然试图了解生成器,而不是关注以下内容:

function* powerSeries(number,power) {
  let base = number;
  while (true) {
    yield Math.pow(base, power);
    base++
  }
}

let n = powerSeries(3,2)
n.next() // value: 9
n.next() // value: 16
...

我尝试过:

function* powerSeries(number,power) {
  let base = number;
  yield Math.pow(base, power);
  return base++ // was trying to understand what happens if using return
}

let n = powerSeries(3,2)
n.next() // value: 9
n.next() // value: 3 But how ????

我可以理解,帖子增量未完成,因为它不在循环内。因此,它的基数保持为3。但是它如何变成1的幂,所以结果为3?

javascript ecmascript-6 generator yield
1个回答
0
投票

来自yield

yield

[...]

A Description语句已到达。在这种情况下,生成器的执行结束,并且return返回到调用方,其中returnIteratorResult语句指定的值,完成是value

return
© www.soinside.com 2019 - 2024. All rights reserved.