【问题标题】:Object.entries is not a function in NWJS 0.36.3 (Node 11.10.1)Object.entries 不是 NWJS 0.36.3(节点 11.10.1)中的函数
【发布时间】:2019-03-08 13:35:45
【问题描述】:

我正在尝试创建一个在对象中将“键”与“值”交换的函数。出于某种原因,我得到一个 TypeError: object.entries is not a function。我在这里遗漏了什么或做错了什么?

Object.defineProperty(Object.prototype, 'swapKeysValues', {
    value: function() {
        let obj = {};
        this.entries().forEach(([key, value]) => {
            obj[value] = key;
        });
        return obj;
    }
});

进一步测试显示:

let foo = { a: 1, b: 2, c: 3 }
typeof foo // "object"
foo instanceof Object // true
foo.entries // undefined
foo.entries() // Uncaught TypeError: foo.entries is not a function

更新:

所以我学到的是对象(即 let foo = { a: 1 })不继承 .entries、.keys 或 .values 函数作为属性,我必须通过调用 Object.entries( foo) 正如 tehhowch / SylvainF 所指出的。工作代码:

Object.defineProperty(Object.prototype, 'swapKeysValues', {
    value: function() {
        let obj = {};
        Object.entries(this).forEach(([key, value]) => {
            obj[value] = key;
        });
        return obj;
    }
});

// Example
let foo = { a: 1, b: 2, c: 3 }
foo.swapKeysValues()

// Output
{1: "a", 2: "b", 3: "c"}

谢谢 tehhowch / SylvainF!

【问题讨论】:

  • 如果您使用关键字function 创建函数,this 将引用函数本身。您的函数中没有定义 entries 方法。
  • Object.entries(someObj).
  • 我不明白,考虑到我正在开发人员工具控制台中运行上述“foo”测试代码。在 Chrome 72 浏览器中的结果相同。

标签: node.js nwjs


【解决方案1】:

就像@tehhowch 在 cmets 中所说,语法是 Object.entries(foo)

可以看到MDn页面:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/entries

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多