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

后端 未结 10 2118
离开以前
离开以前 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:45

    Compiling other answers:

    Object

    var test = {};
    

    When using a number as a new property's key, the number turns into a string:

    test[2300] = 'Some string';
    console.log(test['2300']);
    // Output: 'Some string'
    

    When accessing the property's value using the same number, the number is turned into a string again:

    console.log(test[2300]);
    // Output: 'Some string'
    

    When getting the keys from the object, though, they aren't going to be turned back into numbers:

    for (var key in test) {
        console.log(typeof key);
    }
    // Output: 'string'
    

    Map

    ECMAScript 6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:

    var test = new Map();
    test.set(2300, 'Some string');
    console.log(test.get(2300));
    // Output: 'Some string'
    

    No type conversion is performed, for better and for worse:

    console.log(test.get('2300'));
    // Output: undefined
    test.set('2300', 'Very different string');
    console.log(test.get(2300));
    // Output: 'Some string'
    

提交回复
热议问题