Check if property name is array index

我与影子孤独终老i 提交于 2019-12-18 09:13:28

问题


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


来源:https://stackoverflow.com/questions/38163612/check-if-property-name-is-array-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!