Reputation: 478
Can anybody please explain this behavior of javascript arrays
//create an empty array
var arr=[];
//added an entry with index Number.MAX_VALUE
arr[Number.MAX_VALUE]="test"
//On printing the array, its showing as empty
arr
//[]
//even its length=0
arr.length
//0
//on accessing the same value its showing the correct value
arr[Number.MAX_VALUE]
//"test"
I have tried this with Number.MIN_VALUE.
Does anybody know the reason behind this?
Upvotes: 4
Views: 262
Reputation: 461
It takes Number.MAX_VALUE not like an index, but like a property name. You can see same behavior for any string value
A property name P (in the form of a string value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to (2^32)−1
(http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf page65, section 15.4)
Upvotes: -1
Reputation: 224942
Number.MAX_VALUE
is not a valid array index. According to the spec:
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.
Any property name that’s not an array index according to this definition is just a regular property name, as you can see by the key ordering (array indexes are in order; other properties are in insertion order):
var a = {};
a.prop = 'foo';
a[2 ** 32 - 2] = 'bar';
a[Number.MAX_VALUE] = 'baz';
console.log(Object.keys(a));
// ["4294967294", "prop", "1.7976931348623157e+308"]
Upvotes: 7