检查属性名称是否为数组索引 [英] Check if property name is array index

查看:130
本文介绍了检查属性名称是否为数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为数组分配一些属性,但前提是它们是数组索引。否则一些实现可能会将底层结构切换到哈希表,我不希望这样。

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.

例如,这些是数组索引: 012 344294967294

For example, these are array indices: "0", "1", "2", "3", "4", "4294967294"

但这些不是:abcd0.1 - 0 - 121e34294967295

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?

推荐答案

在ECMAScript 5中,阵列索引定义如下:

In ECMAScript 5, Array indices are defined as follows:


属性名称​​ P (以String值的形式)是数组
index
当且仅当 ToString ToUint32 P ))等于
P ToUint32 P )不等于2 32 -1。

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

然后,代码将是

function isArrayIndex(str) {
  return (str >>> 0) + '' === str && str < 4294967295
}

一步一步,

P >>> 0


  • ToString(ToUint32( P ))可以完成通过将空字符串与添加运算符连接起来。

  • ToString(ToUint32(P)) can be done by concatenating the empty string with the addition operator.

    (P >>> 0) + ''
    


  • ToString(ToUint32( P ))等于 P 可以用严格等于运营商

    (P >>> 0) + '' === P
    

    请注意,这也将确保 P 确实是String值的形式。

    Note this will also ensure that P really was in the form of a String value.

    ToUint32( P )不等于2 32 -1可以用严格的不等于运营商

    ToUint32(P) is not equal to 232−1 can be checked with the strict does-not-equal operator

    (P >>> 0) !== 4294967295
    

    但是一旦我们知道ToString(ToUint32( P ))等于 P ,以下之一就足够了:

    But once we know ToString(ToUint32(P)) is equal to P, one of the following should be enough:

    P !== "4294967295"
    P < 4294967295
    


  • 这篇关于检查属性名称是否为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆