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
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
).