【问题标题】:JavaScript "associative" array accessJavaScript“关联”数组访问
【发布时间】:2011-02-01 05:41:54
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • “只是一个非显式字符串”是什么意思?

标签: javascript arrays associative


【解决方案1】:

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

给定:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    但是,我认为您没有发布无效代码?

    【讨论】:

      【解决方案3】:

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

      var bowl = {
        fruit: "apple",
        nuts: "brazil"
      };
      
      alert(bowl.fruit);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多