Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

javascript - Check if property name is array index

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...