The item exists in the array but it says that the array is 0 length?

前端 未结 1 1302
逝去的感伤
逝去的感伤 2021-01-19 07:36

I can add an item to an array it and I can access that item, but the length reports 0. Why?

var arr = [];
arr[4294967300] = \"My it         


        
1条回答
  •  悲哀的现实
    2021-01-19 08:17

    That's because the index is so big that it gets turned into a property instead, hence the length is 0.

    According to the ECMAScript documentation, a particular value p can only be an array index if and only if:

    (p >>> 0 === p) && (p >>> 0 !== Math.pow(2, 32) - 1)
    

    Where >>> 0 is equivalent to ToUint32(). In your case:

    4294967300 >>> 0 // 4
    

    By definition, the length property is always one more than the numeric value of the biggest valid index; negative indices would give you the same behaviour, e.g.

    arr[-1] = 'hello world';
    arr.length; // 0
    arr['-1']; // 'hello world'
    

    If your numbers range between what's valid (and gets used as an index) and "invalid" (where it gets turned into a property), it would be better to cast all your indices to a string and work with properties all the way (start with {} instead of Array).

    0 讨论(0)
提交回复
热议问题