开发者

Efficient syntax for populating a javascript associative array

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.

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;
item开发者_Python百科Ids["item2"] = 40;
itemIds["item3"] = 72;
...

function getItemId(code){
    return itemIds[code];
}


What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).

You can use JavaScript object literal syntax:

var itemIds = {
    item1: 15,
    item2: 40,
    item3: 72
};

JavaScript object members can be accessed via dot notation or array subscript, like so:

itemIds.item1;
itemIds['item1'];

You'll need to use the second option if you've got the member name as a string.


Try using Object Literal notation to specify your lookup like this:

var itemIds = {
    "item1" : 15,
    "item2" : 40
    ...
};

Access should still work like this:

var item1Value = itemIds["item1"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜