【问题标题】:For-of loop in node --harmony doesn't work with arrays节点中的 for-of 循​​环 --harmony 不适用于数组
【发布时间】:2014-12-13 08:51:32
【问题描述】:

当我使用 --harmony 选项启动节点 v0.11.14 REPL 并尝试 for-of 循​​环时,我得到:

> for (var i of [3, 4, 5]) console.log(i);
TypeError: undefined is not a function

套装也是如此。但它适用于生成器:

> function* Counter() { var n=3; while (n < 7) { yield n++; } }
> var c = new Counter();
> for (var i of c) console.log(i);
3
4
5
6

虽然ecmascript wiki page 的第一个例子是:

for (word of ["one", "two", "three"]) {
    alert(word);
}

MDN pageTraceur docs 包含相同的示例。我没能用谷歌搜索“for-of in nodejs”。它真的应该在 Node 中工作还是我错过了什么?

【问题讨论】:

    标签: javascript node.js ecmascript-6 ecmascript-harmony


    【解决方案1】:

    for .. of 和可迭代对象在 v8 中分别实现。看起来在与节点 0.11.14 捆绑的 v8 中,您只能将其与生成器一起使用。

    您可以检查obj[Symbol.iterator] 属性以查看对象是否可迭代,它应该是一个函数。在我使用 v8 3.29.93 构建的节点中,一切都按预期工作。因此,您可能需要等待下一个 0.11 版本(或 0.12)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-21
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 2020-07-10
      • 1970-01-01
      相关资源
      最近更新 更多