javascript" associative"阵列访问 [英] javascript "associative" array access

查看:89
本文介绍了javascript" associative"阵列访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模拟aarray有两个元素:

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);
}

但是每当我尝试使用密钥从代码中访问aarray时只是一个非显式的字符串,我得到了未定义。我是否必须以转义的'key'传递参数。有任何想法吗? tia。

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.

推荐答案

密钥可以是动态计算的字符串。举一个你传递的不起作用的例子。

The key can be a dynamically computed string. Give an example of something you pass that doesn't work.

鉴于:

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

这些对碗的效果都相同对象。然后你可以使用相应的模式来检索值:

Those all have the same effect on the bowl object. 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"];

这篇关于javascript" associative"阵列访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆