如何动态引用对象? [英] How do I reference an object dynamically?

查看:59
本文介绍了如何动态引用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我有一个对象:

In Javascript, I have an object:

obj = { one: "foo", two: "bar" };

现在,我想要这样做

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?

推荐答案

简答: obj [a]

长答案: obj.field 只是<$ c $的简写c> obj [field] ,对于特殊情况,其中键是一个没有空格,圆点或其他令人讨厌的东西的常量字符串。在你的问题中,关键不是常数,所以只需使用完整的语法。

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.

这篇关于如何动态引用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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