我有一个包含两个元素的简单模拟数组:
bowl["fruit"] = "apple";
bowl["nuts"] = "brazilian";
我可以通过这样的事件访问该值:
onclick = "testButton00_('fruit')">with `testButton00_`
function testButton00_(key){
var t = bowl[key];
alert("testButton00_: value = "+t);
}
但是,每当我尝试使用只是一个非显式字符串的键从代码中访问数组时,我都会得到undefined。我是否必须以某种方式传递带有转义“ key ”的参数?
最佳答案
键可以是动态计算的字符串。举例说明您通过但不起作用的内容。
给定:
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"];
关于JavaScript "associative"数组访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2524413/