JavaScript“关联”数组访问
我有一个包含两个元素的简单模拟数组:
bowl["fruit"] = "apple";
bowl["nuts"] = "brazilian";
我可以通过如下事件访问该值:
onclick = "testButton00_('fruit')">with `testButton00_`
function testButton00_(key){
var t = bowl[key];
alert("testButton00_: value = "+t);
}
但是,每当我尝试使用只是非显式字符串的键从代码内访问该数组时,我都会得到 未定义。。我是否必须以某种方式传递带有转义“密钥”的参数?
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. Do I have somehow have to pass the parameter with the escaped 'key'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
键可以是动态计算的字符串。举一个你通过但不起作用的例子。
给定:
您可以说:
或:
甚至:
或者如果您确实想要这样做:
这些对
bowl
对象都有相同的效果。然后您可以使用相应的模式来检索值:The key can be a dynamically computed string. Give an example of something you pass that doesn't work.
Given:
You can say:
Or:
Or even:
Or if you really want to:
Those all have the same effect on the
bowl
object. And then you can use the corresponding patterns to retrieve values:如果您不想转义密钥,可以使用 JSON:
You could use JSON if you don’t want to escape the key:
我不确定我是否理解你。您可以确保密钥是这样的字符串
或者您可以检查密钥是否存在:
但是,我认为您没有发布无效代码?
I am not sure I understand you. You can make sure the key is a string like this
Or you can check if the key exists:
However, I don't think you have posted the non-working code?