我想创建一个 {key:value}
类型的对象其中键名是可变的。此类对象必须提供给 chrome.storage.<storageType>.set(keys, function(){...})
SO 上有很多相关问题并提供有效答案,但我无法找到该问题的合适解释。它归结为在 JSON 对象上设置属性。我做了这个测试:
var desiredKey = "123",
desiredValue = "Value for key 123",
foo;
// 1-The basic: Using a literal
console.log({ "123": desiredValue });
// 2-The problem occurs when the key name is not a literal
console.log({ desiredKey: desiredValue });
// 3-The solution is to assign a key explicitely
foo = {};
foo[desiredKey] = desiredValue;
console.log(foo);
结果:
Object { 123: "Value for key 123" } <-- Literal
Object { desiredKey: "Value for key 123" } <-- Variable (wrong)
Object { 123: "Value for key 123" } <-- Assignment (ok)
问题:
- 为什么方法 2 失败?存储了什么?
desiredKey
的引用/地址? - 方法 3 是最简单的吗?或者有一个单一指令的解决方案吗?
最佳答案
方法4
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets
[]
, that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already.
var desiredKey = "123",
desiredValue = "Value for key 123",
foo = { [desiredKey]: desiredValue };
console.log(foo);
关于javascript - 如何创建一个 {key :value} object from two variables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932613/