用于填充 javascript 关联数组的有效语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3831181/
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
Efficient syntax for populating a javascript associative array
提问by Jimbo
I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.
我有一个自动完成文本框,用户可以在其中键入项目代码,并且需要在 javascript 中找出该项目代码的 ID 号。
An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:
关联数组是我认为应该完成的方式,但以下内容似乎有点冗长,我希望有人有更好的方法来做到这一点或我在下面的简写:
var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...
function getItemId(code){
return itemIds[code];
}
回答by Skilldrick
What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).
您正在做的不是数组 - 它是一个对象(JavaScript 中的对象与 PHP 中的关联数组等效)。
You can use JavaScript object literal syntax:
您可以使用 JavaScript 对象字面量语法:
var itemIds = {
item1: 15,
item2: 40,
item3: 72
};
JavaScript object members can be accessed via dot notation or array subscript, like so:
JavaScript 对象成员可以通过点符号或数组下标访问,如下所示:
itemIds.item1;
itemIds['item1'];
You'll need to use the second option if you've got the member name as a string.
如果您将成员名称作为字符串,则需要使用第二个选项。
回答by Simon Steele
Try using Object Literal notation to specify your lookup like this:
尝试使用 Object Literal 表示法来指定您的查找,如下所示:
var itemIds = {
"item1" : 15,
"item2" : 40
...
};
Access should still work like this:
访问应该仍然像这样工作:
var item1Value = itemIds["item1"];

