I want to assign some properties to an array, but only if they are array indices. Otherwise some implementations might switch the underlying structure to a hash table and I
In ECMAScript 5, Array indices are defined as follows:
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 232−1.
(The definition in ECMAScript 2015 is worded differently but should be equivalent.)
Then, the code would be
function isArrayIndex(str) {
return (str >>> 0) + '' === str && str < 4294967295
}
Step by step,
ToUint32(P) can be done by shifting 0 bits with the unsigned right shift operator
P >>> 0
ToString(ToUint32(P)) can be done by concatenating the empty string with the addition operator.
(P >>> 0) + ''
ToString(ToUint32(P)) is equal to P can be checked with the strict equals operator.
(P >>> 0) + '' === P
Note this will also ensure that P really was in the form of a String value.
ToUint32(P) is not equal to 232−1 can be checked with the strict does-not-equal operator
(P >>> 0) !== 4294967295
But once we know ToString(ToUint32(P)) is equal to P, one of the following should be enough:
P !== "4294967295"
P < 4294967295