[英]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.