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

问题描述

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

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 >>> 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 -1可以用

    ToUint32(P) is not equal to 2−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
    


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

    09-27 07:35