为什么Javascript数组索引最多为4294967294而不是4294967295? [英] Why is a Javascript Array index at most 4294967294 but not 4294967295?

查看:164
本文介绍了为什么Javascript数组索引最多为4294967294而不是4294967295?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript的索引是32位,因此似乎数组索引应该能够达到4294967295,共计4294967296个元素。但实际上最高的索引是4294967294.由于数组有一个 length 属性,我没有看到将null作为最后一个元素的原因。有没有理由最大索引是4294967294而不是4294967295?

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 4294967294. Since an array has a length property, I don't see a reason for having a null as the last element. Is there a reason the maximum index is 4294967294 but not 4294967295?

推荐答案

这是因为当您使用<$创建数组时c $ c>数组构造函数您可以提供一个可选的长度,如下所示:

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

new Array(length);

数组的长度是32位无符号整数。因此,数组的长度范围可以从 0 Math.pow(2,32) - 1 ,这是 4294967295

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.

对于长度 n 的数组索引范围从 0 n - 1 。因此,JavaScript数组的最大索引是(Math.pow(2,32) - 1) - 1 Math.pow(2,32) ) - 2 ,这是 4294967294

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.

因此,一个JavaScript数组可能包含一个最多 4294967295 元素而非 4294967296 元素。

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.

这篇关于为什么Javascript数组索引最多为4294967294而不是4294967295?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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