如何访问动态属性:objectName。{variable} [英] How to access a dynamic property: objectName.{variable}
问题描述
我需要访问
objectName.myID
但myID部分是动态生成的..
but the "myID" part is dynamically generated..
我该怎么做?
我试过
this['objectName.'+ variable]
我讨厌使用eval ......
i'd hate to use eval...
ps
顺便发生在函数(本地范围)中..
ps this happens in a function (local scope) by the way..
推荐答案
你可以访问对象属性有两种方式:
o.propertyname
//or
o.["propertyname"]
使用括号表示法时,必须将属性名称放在引号中,否则它将被解释为变量名称(在您的情况下,它正是您想要的)。因此,在您将属性名称存储为字符串的情况下,可行的方法是:
When using the bracket notation you have to put the propertyname in quotes or else it will be interpreted as a variable name (which in your case is exactly what you want). So in your case where you have stored the name of the property as a string, the way to go would be:
var variable = "propertyname";
o[variable];
/* /\ variable is replace with it's string representation "propertyname" */
您甚至可以通过这种方式调用方法:
You can even call methods this way:
var o = {};
var functionname = 'toString';
o[functionname]();
你可以混合两种符号,你的例子如下:
You can mix both notations, your example would look like:
var obj = 'objectName';
var prop = 'myID';
this[obj][prop]
// or this is possible too:
this.objectName[prop]
这篇关于如何访问动态属性:objectName。{variable}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!