javascript“关联”数组访问

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2524413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:44:50  来源:igfitidea点击:

javascript "associative" array access

javascriptarraysassociative

提问by cp.

I have a simple simulated aarray 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 aarray from within code with a key that is just a non-explicit string I get undefined. Do I have somehow have to pass the parameter with the escaped 'key'. Any ideas? tia.

但是,每当我尝试使用一个非显式字符串的键从代码中访问数组时,我都会得到未定义。我是否必须以某种方式使用转义的“键”传递参数。有任何想法吗?蒂亚。

回答by Daniel Earwicker

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 bowlobject. And then you can use the corresponding patterns to retrieve values:

这些都对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"];

回答by douwe

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?

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

回答by Raj Kaimal

You could use JSON if you dont want to escape the key.

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

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

alert(bowl.fruit);