Array.length gives incorrect length

后端 未结 4 1914
我在风中等你
我在风中等你 2020-12-03 16:41

If I have an array having object as values at the indices like:

var a = [];
a[21] = {};
a[90] = {};
a[13] = {};
alert(a.length); // outputs 91
4条回答
  •  情歌与酒
    2020-12-03 17:44

    The array in JavaScript is a simple zero-based structure. The array.length returns the n + 1 where n is the maximum index in an array.

    That's just how it works - when you assign 90'th element and this array's length is less than 90, it expands an array to 90 and sets the 90-th element's value. All missing values are interpreted as null.

    If you try the following code:

    var a = [];
    a[21] = {};
    a[90] = {};
    a[13] = {};
    console.log(JSON.stringify(a));
    

    You will get the following JSON:

    [null,null,null,null,null,null,null,null,null,null,null,null,null,{},null,null,null,null,null,null,null,{},null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,{}]

    Moreover, array.length is not a readonly value.
    If you set a length value less than the current, then the array will be resized:

     var arr = [1,2,3,4,5];
     arr.length = 3;
     console.log(JSON.stringify(arr));
     // [1,2,3]
    

    If you set a length value more than the current, then the array will be expanded as well:

     var arr = [1,2,3];
     arr.length = 5;
     console.log(JSON.stringify(arr));
     // [1,2,3,null,null]
    

    In case you need to assign such values, you can use JS objects.
    You can use them as associative array and assign any key-value pairs.

    var a = {};
    a[21] = 'a';
    a[90] = 'b';
    a[13] = 'c';
    a['stringkey'] = 'd';
    a.stringparam = 'e'; // btw, a['stringkey'] and a.stringkey is the same
    
    console.log(JSON.stringify(a)); 
    // returns {"13":"c","21":"a","90":"b","stringkey":"d","stringparam":"e"}
    
    console.log(Object.keys(a).length);
    // returns 5
    

提交回复
热议问题