An element exists in the array, but it says the array is 0 length?

I can add an element to the array, and I can access this element, but length reports 0 . Why?

 var arr = []; arr[4294967300] = "My item"; console.log(arr[4294967300], arr.length); // Outputs "My item", 0 
+4
source share
1 answer

This is because the index is so large that instead it turns into a property, so the length is 0.

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

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

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

 4294967300 >>> 0 // 4 

By definition, the length property is always greater than the numeric value of the largest valid index; negative indices will give you the same behavior, for example.

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

If your numbers vary between what really (and is used as an index) and "invalid" (where it turns into a property), it would be better if all indexes are displayed in a row and work with the properties of all (start with {} instead of Array ) .

+6
source

Source: https://habr.com/ru/post/1440019/


All Articles