4

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 Answer 1

7

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
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.