问题
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 don't want that.
For example, these are array indices: "0", "1", "2", "3", "4", "4294967294"
But these are not: "abcd", "0.1", "-0", "-1", " 2", "1e3", "4294967295"
Is there an easy way to test if a string is an array index?
回答1:
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 >>> 0ToString(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) + '' === PNote 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) !== 4294967295But once we know ToString(ToUint32(P)) is equal to P, one of the following should be enough:
P !== "4294967295" P < 4294967295
来源:https://stackoverflow.com/questions/38163612/check-if-property-name-is-array-index