Efficient syntax for populating a javascript associative array

前端 未结 2 1883
挽巷
挽巷 2020-12-29 06:41

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 arra

相关标签:
2条回答
  • 2020-12-29 07:06

    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.

    0 讨论(0)
  • 2020-12-29 07:14

    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 讨论(0)
提交回复
热议问题