【问题标题】:Is it possible to use ES6 For..Of on an Object instead of an Array? [duplicate]是否可以在对象而不是数组上使用 ES6 For..Of? [复制]
【发布时间】:2015-10-14 10:59:59
【问题描述】:

在 babel-node 我得到 REPL

TypeError: undefined is not a function

尝试在对象上使用 For..Of 进行迭代时。我不明白为什么 for..in 会起作用,但 for..of 不会。只适用于数组吗?

const config = { base: 'iei', url: 'www.' }

for (let i of config) { console.log(i); }

【问题讨论】:

  • 您希望它记录什么?
  • 我希望它记录 'iei' 和 'www'
  • 是的,看起来一模一样。不过我的标题更明确。

标签: ecmascript-6


【解决方案1】:

不,for of 用于 iterables。并非所有对象都是可迭代的。不过,您可以为您的对象创建自定义迭代器:

Object.values = function* (o) {
    for (let k of Object.keys(o))
        yield o[k];
};

for (let i of Object.values(config)) console.log(i); // 'iei', 'www.'

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2016-11-28
    • 2019-04-13
    相关资源
    最近更新 更多