最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I reference an object dynamically? - Stack Overflow

programmeradmin1浏览0评论

In Javascript, I have an object:

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?

In Javascript, I have an object:

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?

Share Improve this question edited Jan 22, 2010 at 17:28 Issac Kelly asked Oct 4, 2008 at 4:23 Issac KellyIssac Kelly 6,3596 gold badges44 silver badges51 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 20

short answer: 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. in your question, the key wasn't a constant, so simply use the full syntax.

Like this:

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"

发布评论

评论列表(0)

  1. 暂无评论