簡體   English   中英

JavaScript“關聯”數組訪問

[英]JavaScript “associative” array access

我有一個包含兩個元素的簡單模擬數組:

bowl["fruit"] = "apple";
bowl["nuts"] = "brazilian";

我可以通過這樣的事件訪問該值:

onclick = "testButton00_('fruit')">with `testButton00_`

function testButton00_(key){
    var t = bowl[key];
    alert("testButton00_: value = "+t);
}

但是,每當我嘗試使用一個非顯式字符串的鍵從代碼中訪問數組時,我都會得到undefined 我是否必須以某種方式使用轉義的“鍵”傳遞參數?

鍵可以是動態計算的字符串。 舉一個你通過但不起作用的例子。

鑒於:

var bowl = {}; // empty object

你可以說:

bowl["fruit"] = "apple";

或者:

bowl.fruit = "apple"; // NB. `fruit` is not a string variable here

甚至:

var fruit = "fruit";
bowl[fruit] = "apple"; // now it is a string variable! Note the [ ]

或者,如果您真的想:

bowl["f" + "r" + "u" + "i" + "t"] = "apple";

這些都對bowl對象具有相同的效果。 然后您可以使用相應的模式來檢索值:

var value = bowl["fruit"];
var value = bowl.fruit; // fruit is a hard-coded property name
var value = bowl[fruit]; // fruit must be a variable containing the string "fruit"
var value = bowl["f" + "r" + "u" + "i" + "t"];

我不確定我理解你。 您可以確保密鑰是這樣的字符串

if(!key) {
  return;
}
var k = String(key);
var t = bowl[k];

或者您可以檢查密鑰是否存在:

if(typeof(bowl[key]) !== 'undefined') {
  var t = bowk[key];
}

但是,我認為您沒有發布非工作代碼?

如果您不想轉義密鑰,可以使用 JSON:

var bowl = {
  fruit: "apple",
  nuts: "brazil"
};

alert(bowl.fruit);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM