In Javascript, I have an object:
在Javascript中,我有一个对象:
obj = { one: "foo", two: "bar" };
Now, I want do do this
现在,我想这样做
var a = 'two';
if(confirm('Do you want One'))
{
a = 'one';
}
alert(obj.a);
But of course it doesn't work. What would be the correct way of referencing this object dynamically?
但它当然不起作用。动态引用这个对象的正确方法是什么?
3 个解决方案
#1
16
short answer: obj[a]
简短的回答:obj[一]
long answer: obj.field
is just a shorthand for obj["field"]
, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.
长答:obj。字段只是obj["field"]的简写,在特殊情况下,键是一个常量字符串,没有空格、点或其他讨厌的东西。在您的问题中,键不是常量,因此只需使用完整的语法。
#2
6
Like this:
是这样的:
obj[a]
#3
2
As a side note, global variables are attached to the "window" object, so you can do
作为补充说明,全局变量附加到“窗口”对象,因此您可以这样做
var myGlobal = 'hello';
var a = 'myGlobal';
alert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);
This will alert "hello, hello, hello"
它会提示“你好,你好,你好”
#1
16
short answer: obj[a]
简短的回答:obj[一]
long answer: obj.field
is just a shorthand for obj["field"]
, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.
长答:obj。字段只是obj["field"]的简写,在特殊情况下,键是一个常量字符串,没有空格、点或其他讨厌的东西。在您的问题中,键不是常量,因此只需使用完整的语法。
#2
6
Like this:
是这样的:
obj[a]
#3
2
As a side note, global variables are attached to the "window" object, so you can do
作为补充说明,全局变量附加到“窗口”对象,因此您可以这样做
var myGlobal = 'hello';
var a = 'myGlobal';
alert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);
This will alert "hello, hello, hello"
它会提示“你好,你好,你好”