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 item";
console.log(arr[4294967300], arr.length); // Outputs "My item", 0
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Where
>>> 0is equivalent toToUint32(). In your case:By definition, the
lengthproperty is always one more than the numeric value of the biggest valid index; negative indices would give you the same behaviour, e.g.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 ofArray).