javascript"associative"数组访问

cp.*_*cp. 11 javascript arrays associative

我有一个简单的模拟阵列,有两个元素:

bowl["fruit"]="apple";
bowl["nuts"]="brazilian";
Run Code Online (Sandbox Code Playgroud)

我可以使用以下事件访问该值:

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

function testButton00_(key){
    var t = bowl[key];
    alert("testButton00_: value = "+t);
}
Run Code Online (Sandbox Code Playgroud)

但是每当我尝试使用只是非显式字符串的键从代码中访问aarray时,我都会得到未定义的.我是否必须以转义的'key'传递参数.有任何想法吗?TIA.

Dan*_*ker 20

密钥可以是动态计算的字符串.举一个你传递的不起作用的例子.

鉴于:

var bowl = {}; // empty object
Run Code Online (Sandbox Code Playgroud)

你可以说:

bowl["fruit"] = "apple";
Run Code Online (Sandbox Code Playgroud)

要么:

bowl.fruit = "apple"; // NB. `fruit` is not a string variable here
Run Code Online (Sandbox Code Playgroud)

甚至:

var fruit = "fruit";
bowl[fruit] = "apple"; // now it is a string variable! Note the [ ]
Run Code Online (Sandbox Code Playgroud)

或者,如果你真的想:

bowl["f" + "r" + "u" + "i" + "t"] = "apple";
Run Code Online (Sandbox Code Playgroud)

这些都对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"];
Run Code Online (Sandbox Code Playgroud)