gpt4 book ai didi

JavaScript "associative"数组访问

转载 作者:可可西里 更新时间:2023-11-01 02:19:09 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com