如何将变量插入JavaScript对象中作为键? [英] How do I interpolate a variable as a key in a JavaScript object?

查看:128
本文介绍了如何将变量插入JavaScript对象中作为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用变量 a 的值作为查找属性的键?我希望能够说: b [无论如何] 并将此返回20:

How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`

我在询问是否有可能在创作过程中 b ,让它包含无论如何:20 而不是 a:20 其中whatever本身就是一个变量。也许可以使用 eval

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

推荐答案

var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20

这篇关于如何将变量插入JavaScript对象中作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆