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

后端 未结 10 2112
离开以前
离开以前 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 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[] object.

提交回复
热议问题