访问JavaScript对象变量属性[复制]

时间:2022-08-27 17:37:39

Possible Duplicate:
How to create object property from variable value in javascript?

可能重复:如何在javascript中从变量值创建对象属性?

How to access property name stored in variable like this?

如何访问像这样存储在变量中的属性名?

var obj = {};

obj.foo = 'bar';
var propName = 'foo';

//I want something like this:
console.debug(obj.{propName});

Is there any possibility to do it without using eval()?

是否有可能不使用eval()进行此操作?

2 个解决方案

#1


1  

You can access the objects properties like:

您可以访问对象属性,如:

myObject['property_name']

Try:

试一试:

var obj = {};
obj.foo = 'bar';
var propName = 'foo';
console.log(obj[propName]);

#2


0  

Of cource you can:

的,您可以:

​(function(){
    var obj = {};
    obj.foo = 'bar';

    var key = 'foo';

    document.write(obj[key]);
})()​

#1


1  

You can access the objects properties like:

您可以访问对象属性,如:

myObject['property_name']

Try:

试一试:

var obj = {};
obj.foo = 'bar';
var propName = 'foo';
console.log(obj[propName]);

#2


0  

Of cource you can:

的,您可以:

​(function(){
    var obj = {};
    obj.foo = 'bar';

    var key = 'foo';

    document.write(obj[key]);
})()​