【发布时间】: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 浏览器中的结果相同。