13

我有一个包含两个元素的简单模拟数组:

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

我可以通过这样的事件访问该值:

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

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

但是,每当我尝试使用只是非显式字符串的键从代码中访问数组时,我都会得到undefined。我是否必须以某种方式使用转义的“密钥”传递参数?

4

3 回答 3

24

键可以是动态计算的字符串。举一个你通过但不起作用的例子。

鉴于:

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"];
于 2010-03-26T15:31:13.043 回答
0

我不确定我是否理解你。您可以确保密钥是这样的字符串

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

或者您可以检查密钥是否存在:

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

但是,我认为您没有发布非工作代码?

于 2010-03-26T15:35:20.373 回答
0

如果您不想转义密钥,可以使用 JSON:

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

alert(bowl.fruit);
于 2010-03-26T15:36:08.783 回答