2015-10-03 106 views
0

获得价值,我有以下代码:使用JavaScript函数参数从对象

var myObj = {apples:"five", pears:"two"}; 

function myFunction(x) { 
    alert(myObj.x); 
}; 

当我运行myFunction(apples)我没有得到警告说five,但我得到一个警告说undefined

我如何使用函数参数x与对象myObj

我想是可以说“十二五”,而不是“未定义”结果我想要的结果。

对不起,我不得不问这样一个愚蠢的问题,但我刚开始学习Javascript,我无法在任何地方找到它,因此我在这里问它。我希望你能帮助我:)

+0

使用如下括号:'myObj [x]' – Manu

回答

2

使用[]符号:

var myObj = {apples:"five", pears:"two"}; 

function myFunction(x) { 
    alert(myObj[x]); 
}; 

myFunction('apples') 
+0

非常感谢! – Megarobo

1

你必须要通过产权南e作为一个字符串。在功能使用括号符号([])内进行访问而不是使用点号(.)。

var myObj = {apples:"five", pears:"two"}; 

function myFunction(x) { 
    alert(myObj[x]); 
}; 

myFunction("apples"); 
+0

非常感谢! – Megarobo