Geo*_*Geo 39 javascript dictionary
如何使用变量的值a作为查找属性的键?我希望能够说:b["whatever"]并且这个回报20:
var a = "whatever";
var b = {a : 20}; // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
Run Code Online (Sandbox Code Playgroud)
我在询问是否有可能在创建过程中b,让它包含"whatever":20而不是a:20变量中的"无论什么".也许eval可以使用?
mVC*_*Chr 47
var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
Run Code Online (Sandbox Code Playgroud)
小智 39
这适用于Firefox 39和Chrome 44.不了解其他浏览器.它也不适用于nodejs v0.12.7.
var a = "whatever";
var b = { [a]: 20 };
console.log(b["whatever"]); // shows 20
Run Code Online (Sandbox Code Playgroud)
也就是说,要插入变量,请将其括在括号中.
我不确定这是否是任何标准的一部分.最初,我在这里看到了这样的语法:https://hacks.mozilla.org/2015/07/es6-in-depth-classes/作者定义:
[functionThatReturnsPropertyName()] (args) { ... }
Run Code Online (Sandbox Code Playgroud)
我也不确定你是否应该使用这种语法.它并不广为人知.您团队中的其他成员可能无法理解代码.
var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37
Run Code Online (Sandbox Code Playgroud)
'a'是一个带有值的字符串'a'.a是一个带有值的变量'whatever'.
好问题.我有时间试图用下划线来解决这个问题,但答案可能不是更简单:
var a = "whatever";
var b = {a : 20};
var array = [a, b]
var answer = _.object([[array]])// {whatever: {a:20}}//NOTICE THE DOUBLE SET OF BRACKETS AROUND [[array]]
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
30962 次 |
| 最近记录: |