Why is a Javascript Array index at most 4294967294 but not 4294967295?

后端 未结 3 493
逝去的感伤
逝去的感伤 2020-12-11 01:45

Javascript\'s index is 32 bit, so it seems that the array index should be able to go up to 4294967295 for a total of 4294967296 elements. But in fact the highest index is 4

相关标签:
3条回答
  • 2020-12-11 02:20

    This is because when you create an array using the Array constructor you may supply it an optional length as follows:

    new Array(length);
    

    The length of an array is a 32-bit unsigned integer. Hence the length of the array may range from 0 to Math.pow(2, 32) - 1 which is 4294967295.

    For an array of length n the indices range from 0 to n - 1. Hence the maximum index of a JavaScript array is (Math.pow(2, 32) - 1) - 1 or Math.pow(2, 32) - 2, which is 4294967294.

    Thus a JavaScript array may hold a maximum of 4294967295 elements and not 4294967296 elements.

    I know. It's pretty illogical, but then again one element won't make a lot of difference.

    0 讨论(0)
  • 2020-12-11 02:29

    javascript array can hold 2^32-1=4294967295.
    but array indexes start from 0 thats why ,4294967295-1=4294967294

    0 讨论(0)
  • 2020-12-11 02:34

    The ECMA-262 specification (section 15.4) says:

    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 spec also says that the length property of an array is always less than 232. That would seem to exclude 4294967295 as an array index.

    0 讨论(0)
提交回复
热议问题