使用 javascript 函数参数从对象中获取值
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/en-US/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");
我有以下代码:
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/en-US/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");