javascript如何使用变量引用对象
我有一个像这样的javascript对象javascript如何使用变量引用对象,javascript,object,Javascript,Object,我有一个像这样的javascript对象 var obj={ a:{x: "someValue", y:"anotherValue"}, b:{x: "bValue", y:"anotherbValue"} }; function(some_value){ alert("some_value is " + some_value + " with type " + typeof some_value); // prints some_value is a wi
var obj={
a:{x: "someValue", y:"anotherValue"},
b:{x: "bValue", y:"anotherbValue"}
};
function(some_value){
alert("some_value is " + some_value + " with type " + typeof some_value);
// prints some_value is a with type string
var t;
t=obj[some_value]["x"]; // doesn't work
some_value="a";
t=obj[some_value]["x"]; // this does work
t=obj["a"]["x"]; // and so does this
}
我试着这样引用它
var obj={
a:{x: "someValue", y:"anotherValue"},
b:{x: "bValue", y:"anotherbValue"}
};
function(some_value){
alert("some_value is " + some_value + " with type " + typeof some_value);
// prints some_value is a with type string
var t;
t=obj[some_value]["x"]; // doesn't work
some_value="a";
t=obj[some_value]["x"]; // this does work
t=obj["a"]["x"]; // and so does this
}
我真的很想知道这里发生了什么。理想情况下,我想参考我的
对象,并将值传递给函数。
谢谢我只能假设您的变量
某些值
不能包含值a
。它可能有额外的空格字符。在JS中,当属性不存在时,它返回一个未定义的。对于以下代码,如果变量some_value
中包含的值在obj
中不作为属性存在,则t
未定义
//if some_value is neither a nor b
t = obj[some_value] // t === undefined
如果试图从未定义的值中提取属性,浏览器将报告错误:
//if some_value is neither a nor b
t = obj[some_value]["x"] // error
在尝试访问某个属性之前,可以使用hasOwnProperty()
检查该属性是否存在
你可以做一个“松散检查”,但它不可靠,因为任何“falsy”都会称之为“不存在”,即使有一个值
if(obj[somevalue]){
//is truthy
} else {
//obj[somevalue] either:
//does not exist
//an empty string
//a boolean false
//null
//anything "falsy"
}
对不起,这里有一个输入错误-在真实代码的最后一个对象上没有两个双引号,您可以编辑您的问题。如果some_值
确实是“a”
,那么t=obj[some_值][“x”]
将起作用。您如何调用该函数?+1从警报的输出判断可能是一个空白问题。是的,就是这样-谢谢,至少我不会忘记再次检查,因为我已经摆弄它很久了。谢谢,我使用了您的建议hasOwnProperty,发现它返回false,some_value=“my_lookup_value”空格!啊