Using an integer as a key in an associative array in JavaScript

后端 未结 10 2081
离开以前
离开以前 2020-12-07 15:34

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.

For example:

v         


        
相关标签:
10条回答
  • 2020-12-07 15:58

    As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

    You can create your object:

    var object = {};
    

    And add the values as array works:

    object[1] = value;
    object[2] = value;
    

    This will give you:

    {
      '1': value,
      '2': value
    }
    

    After that you can access it like an array in other languages getting the key:

    for(key in object)
    {
       value = object[key] ;
    }
    

    I have tested and works.

    0 讨论(0)
  • 2020-12-07 15:58

    Use an object - with an integer as the key - rather than an array.

    0 讨论(0)
  • 2020-12-07 16:00

    Get the value for an associative array property when the property name is an integer:

    Starting with an associative array where the property names are integers:

    var categories = [
        {"1": "Category 1"},
        {"2": "Category 2"},
        {"3": "Category 3"},
        {"4": "Category 4"}
    ];
    

    Push items to the array:

    categories.push({"2300": "Category 2300"});
    categories.push({"2301": "Category 2301"});
    

    Loop through the array and do something with the property value.

    for (var i = 0; i < categories.length; i++) {
        for (var categoryid in categories[i]) {
            var category = categories[i][categoryid];
            // Log progress to the console
            console.log(categoryid + ": " + category);
            //  ... do something
        }
    }
    

    Console output should look like this:

    1: Category 1
    2: Category 2
    3: Category 3
    4: Category 4
    2300: Category 2300
    2301: Category 2301
    

    As you can see, you can get around the associative array limitation and have a property name be an integer.

    NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.

    0 讨论(0)
  • 2020-12-07 16:04

    You can just use an object:

    var test = {}
    test[2300] = 'Some string';
    
    0 讨论(0)
提交回复
热议问题