简体   繁体   English

JavaScript“关联”数组访问

[英]JavaScript “associative” array access

I have a simple simulated array with two elements:我有一个包含两个元素的简单模拟数组:

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

I can access the value with an event like this:我可以通过这样的事件访问该值:

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

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

However, whenever I try to access the array from within code with a key that is just a non-explicit string, I get undefined .但是,每当我尝试使用一个非显式字符串的键从代码中访问数组时,我都会得到undefined Do I have somehow have to pass the parameter with the escaped 'key'?我是否必须以某种方式使用转义的“键”传递参数?

The key can be a dynamically computed string.键可以是动态计算的字符串。 Give an example of something you pass that doesn't work.举一个你通过但不起作用的例子。

Given:鉴于:

var bowl = {}; // empty object

You can say:你可以说:

bowl["fruit"] = "apple";

Or:或者:

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

Or even:甚至:

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

Or if you really want to:或者,如果您真的想:

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

Those all have the same effect on the bowl object.这些都对bowl对象具有相同的效果。 And then you can use the corresponding patterns to retrieve values:然后您可以使用相应的模式来检索值:

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

I am not sure I understand you.我不确定我理解你。 You can make sure the key is a string like this您可以确保密钥是这样的字符串

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

Or you can check if the key exists:或者您可以检查密钥是否存在:

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

However, I don't think you have posted the non-working code?但是,我认为您没有发布非工作代码?

You could use JSON if you don't want to escape the 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