[英]Use javascript function parameter to get value from object
我有以下代码:
var myObj = {apples:"five", pears:"two"};
function myFunction(x) {
alert(myObj.x);
};
当我运行myFunction(apples)
,没有得到警告,说five
,但是却得到了警告,说undefined
。
如何通过将函数参数x
与对象myObj
一起使用来获得所需的结果
我想要的结果是说'five'
而不是'undefined'
。
要获取带有字符串的属性,您需要使用方括号myObj [“ name”]
查看以下内容: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors
正确的代码:
var myObj = {apples:"five", pears:"two"};
function myFunction(x) {
alert(myObj[x]);
};
使用[]表示法:
var myObj = {apples:"five", pears:"two"};
function myFunction(x) {
alert(myObj[x]);
};
myFunction('apples')
您必须将属性名称作为字符串传递。 在函数中,请使用方括号( []
)进行访问,而不要使用点( .
)。
var myObj = {apples:"five", pears:"two"};
function myFunction(x) {
alert(myObj[x]);
};
myFunction("apples");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.