Array.length gives incorrect length

后端 未结 4 1913
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    2020-12-03 17:18

    It's because you have a[90] as largest index so the index is starting from 0 to 90 becomes 91 in length.

    And where you didn't pass the values like a[80], etc. javascript will store them as hole i.e. for eg [1, , 3, , ,90] where commas are used indicates the hole in array.

    If you try to access those values then you'll get undefined.

提交回复
热议问题