【问题标题】:What is the correct (spec-wise) behavior of "yield* undefined" & "yield undefined" in ES6?ES6 中“yield* undefined”和“yield undefined”的正确(规范)行为是什么?
【发布时间】:2015-08-12 06:18:44
【问题描述】:

在尝试了解如何使用 KoaJS 时,我开始意识到 yield* undefined 在 babel 和 traceur 之间的行为不同。 Babel 似乎忽略了该语句,而 traceur 抛出了异常。 可以在此处查看示例:Babel - Traceur,或以下:

function* gen() {
  console.log('will \'yield 1\'');
  yield 1;
  console.log('will \'yield undefined\'');
  yield undefined;
  console.log('will \'yield* undefined\'');
  yield* undefined;
  console.log('will \'yield 2\'');
  yield 2;
}

let y = gen();
while(true) {
  try {
    let r = y.next();
    console.log(JSON.stringify(r));
    if(r.done)
      break;
  }
  catch(e) {
    console.log();
    console.log(e);
    console.log();
  };
}

我尝试在spec 中查找它,但结果更加混乱,因为yield 的规范看起来不像yield undefined 应该返回{done: false}(无价值属性),但那是两个转译器中发生了什么(也在上面的示例中)。至于yield*,我没有找到为什么traceur应该抛出的答案。我还没有尝试使用 v8 (node/iojs)。

所以问题是,在这两种情况下正确/预期的行为是什么?

【问题讨论】:

  • 我已经在 babel JS 中添加了一个关于这个问题的bug report
  • 这获得了四票否决权?
  • @Bergi - 这就是我之前在 Meta 上问的问题,这让我获得了第四个 :-)(如果你注意到的话,这是一个老问题)
  • 啊,对,没注意。你did ask at meta?
  • @Bergi 是的......在一些有用的评论(例如添加 sn-p,添加错误报告的链接)之后,有点抨击,再加上更多的反对意见( -2),我删除了那里的那个,我想我已经问完了问题:-)

标签: yield ecmascript-6 babeljs traceur


【解决方案1】:

正如您在引用的规范中看到的那样,对于yield* expressionexpression needs to have a @@iterator property,这需要是一个方法;否则抛出异常。因此,yield* undefined 应该抛出异常,因为undefined 没有@@iterator 属性。

yield undefined 的情况下,应该产生undefined。这也是发生的事情。但是,在您的示例中,您评估 JSON.stringify({value: undefined, done: false}),它返回 '{"done": false}',因为 JSON 中没有 undefined 这样的东西。

【讨论】:

  • 没错。因此,如果您在 Chrome 和 Firefox 中使用适当的标志运行它,您将分别获得 TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefinedTypeError: undefined has no properties
  • 甜蜜。然后是错误报告:-)
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 2023-01-24
相关资源
最近更新 更多