RangeError: invalid array length

當指定一個數組長度為負數、浮點數或超過平臺支援的最大值時(即建立 ArrayArrayBuffer 時,或設定 length 屬性時),會發生 JavaScript 異常“陣列長度無效”。

允許的最大陣列長度取決於平臺、瀏覽器和瀏覽器版本。對於 Array,最大長度為 232-1。對於 ArrayBuffer,在 32 位系統上最大長度為 231-1 (2GiB-1)。從 Firefox 89 版本開始,在 64 位系統上 ArrayBuffer 的最大值為 233 (8GiB)。

注意: ArrayArrayBuffer 是獨立的資料結構(一個的實現不會影響另一個)。

訊息

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

RangeError: Invalid array buffer length (V8-based)
RangeError: length too large (Safari)

錯誤型別

RangeError

哪裡出錯了?

嘗試建立長度無效的 ArrayArrayBuffer 時可能會出現此錯誤,包括:

  • 透過建構函式或設定 length 屬性指定負長度。
  • 透過建構函式或設定 length 屬性指定非整數長度。(ArrayBuffer 建構函式會將長度強制轉換為整數,但 Array 建構函式不會。)
  • 超過平臺支援的最大長度。對於陣列,最大長度為 232-1。對於 ArrayBuffer,在 32 位系統上最大長度為 231-1 (2GiB-1),或在 64 位系統上為 233 (8GiB)。這可能透過建構函式、設定 length 屬性或隱式設定長度屬性的陣列方法(如 pushconcat)發生。

如果您使用建構函式建立 Array,您可能希望改用字面量表示法,因為第一個引數會被解釋為 Array 的長度。否則,您可能希望在設定長度屬性或將其用作建構函式的引數之前限制長度。

示例

無效案例

js
new Array(2 ** 40);
new Array(-1);
new ArrayBuffer(2 ** 32); // 32-bit system
new ArrayBuffer(-1);

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

const b = new Array(2 ** 32 - 1);
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

// Concurrent modification that accidentally grows the array infinitely
const arr = [1, 2, 3];
for (const e of arr) {
  arr.push(e * 10);
}

有效情況

js
[2 ** 40]; // [ 1099511627776 ]
[-1]; // [ -1 ]
new ArrayBuffer(2 ** 31 - 1);
new ArrayBuffer(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(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);

// Because array methods save the length before iterating, it is safe to grow
// the array during iteration
const arr = [1, 2, 3];
arr.forEach((e) => arr.push(e * 10));

另見