动态选择javascript对象属性

时间:2011-05-20 11:42:48

标签: javascript

[如何]我可以实现以下目标?

var object = new Object();
object.field1 = "test1";
object.fiedl2 = "test2";

function showSpecificField(fieldName){
    //get the field Name passed in to function from object
    //something like: return object.fieldName ???
}

alert(showSpecificField("field2"));// should alert the text "test2"

alert(showSpecificField("field1"));// should alert the text "test1"

1 个答案:

答案 0 :(得分:10)

使用square bracket notation

var baz = 'bar';
foo['bar'] === foo.bar === foo[baz]