范围错误:数组长度无效

当指定的数组长度为负数、浮点数或超出平台支持的最大值时(即创建 ArrayArrayBuffer 时,或设置 length 属性时),会发生 JavaScript 异常 "数组长度无效"。

¥The JavaScript exception "Invalid array length" occurs when specifying an array length that is either negative, a floating number or exceeds the maximum supported by the platform (i.e. when creating an Array or ArrayBuffer, or when setting the length property).

允许的最大数组长度取决于平台、浏览器和浏览器版本。对于 Array,最大长度为 232-1。对于 ArrayBuffer,32 位系统上的最大值为 231-1 (2GiB-1)。从 Firefox 版本 89 开始,64 位系统上 ArrayBuffer 的最大值为 233 (8GiB)。

¥The maximum allowed array length depends on the platform, browser and browser version. For Array the maximum length is 232-1. For ArrayBuffer the maximum is 231-1 (2GiB-1) on 32-bit systems. From Firefox version 89 the maximum value of ArrayBuffer is 233 (8GiB) on 64-bit systems.

注意:ArrayArrayBuffer 是独立的数据结构(其中一个的实现不影响另一个)。

¥Note: Array and ArrayBuffer are independent data structures (the implementation of one does not affect the other).

信息

¥Message

RangeError: invalid array length (V8-based & Firefox)
RangeError: Array buffer allocation failed (V8-based)
RangeError: Array size is not a small enough positive integer. (Safari)

错误类型

¥Error type

RangeError

什么地方出了错?

¥What went wrong?

在这些情况下可能会出现无效的数组长度:

¥An invalid array length might appear in these situations:

  • 创建具有负长度的 ArrayArrayBuffer,或为 length 属性设置负值。
  • 创建 Array 或将 length 属性设置为大于 232-1。
  • 创建大于 231-1 (2GiB-1)(在 32 位系统上)或 233(8GiB)(在 64 位系统上)的 ArrayBuffer
  • 创建 Array 或将 length 属性设置为浮点数。
  • Firefox 89 之前:创建大于 231-1 (2GiB-1) 的 ArrayBuffer

如果你使用构造函数创建 Array,你可能需要使用文字表示法,因为第一个参数被解释为 Array 的长度。

¥If you are creating an Array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the Array.

否则,你可能需要在设置 length 属性之前限制长度,或将其用作构造函数的参数。

¥Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.

示例

¥Examples

无效案例

¥Invalid cases

js
new Array(Math.pow(2, 40));
new Array(-1);
new ArrayBuffer(Math.pow(2, 32)); // 32-bit system
new ArrayBuffer(-1);

const a = [];
a.length = a.length - 1; // set the length property to -1

const b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // set the length property to 2^32
b.length = 2.5; // set the length property to a floating-point number

const c = new Array(2.5); // pass a floating-point number

有效案例

¥Valid cases

js
[Math.pow(2, 40)]; // [ 1099511627776 ]
[-1]; // [ -1 ]
new ArrayBuffer(Math.pow(2, 31) - 1);
new ArrayBuffer(Math.pow(2, 33)); // 64-bit systems after Firefox 89
new ArrayBuffer(0);

const a = [];
a.length = Math.max(0, a.length - 1);

const b = new Array(Math.pow(2, 32) - 1);
b.length = Math.min(0xffffffff, b.length + 1);
// 0xffffffff is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)

b.length = 3;

const c = new Array(3);

也可以看看