简体   繁体   English

如何动态引用对象?

[英]How do I reference an object dynamically?

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? 动态引用此对象的正确方法是什么?

short answer: obj[a] 简短回答: obj[a]

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. 很长的答案: obj.field只是obj["field"]的简写,对于特殊情况,键是一个没有空格,圆点或其他令人讨厌的东西的常量字符串。 in your question, the key wasn't a constant, so simply use the full syntax. 在你的问题中,键不是常量,所以只需使用完整的语法。

像这样:

obj[a]

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" 这会警告“你好,你好,你好”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM