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

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

    Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.

    var test = {};
    test[2300] = 'some string';
    console.log(test);
    

提交回复
热议问题