JavaScript中的“关联”数组访问

13

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

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

我可以通过以下事件访问该值:

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

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

然而,每当我尝试使用非显式字符串作为键从代码中访问数组时,我会得到undefined。我是否需要以转义的“key”方式传递参数?


“just a non-explicit string” 是什么意思? - Guffa
3个回答

26

密钥可以是一个动态计算的字符串。举例说明,指出您传递的某些内容无法正常工作。

给定:

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"];

0

我不确定我理解你的意思。你可以确保键是像这样的字符串

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

或者您可以检查该键是否存在:

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

不过,我认为你没有发布不起作用的代码?


0

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

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

alert(bowl.fruit);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接