From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../errors/invalid_array_length/index.html | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/errors/invalid_array_length/index.html (limited to 'files/zh-tw/web/javascript/reference/errors/invalid_array_length') diff --git a/files/zh-tw/web/javascript/reference/errors/invalid_array_length/index.html b/files/zh-tw/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..ee2c5f08e4 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,74 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

訊息

+ +
RangeError: Array length must be a finite positive integer (Edge)
+RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

錯誤類型

+ +

{{jsxref("RangeError")}}

+ +

哪裡錯了?

+ +

一個無效的陣列長度可能發生於以下幾種情形:

+ + + +

為什麼 Array  和 ArrayBuffer 的長度有限?   Array 和 ArrayBuffer 的屬性以一個32位元的非負整數表使,因此僅能儲存 0 到 232-1 的數值。

+ +

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.

+ +

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

+ +

示例

+ +

無效的案例

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // set -1 to the length property
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // set 2^32 to the length property
+
+ +

有效的案例

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff 是 2^32 - 1 的十六進位表示
+// 也可以寫成 (-1 >>> 0)
+
+ +

參見

+ + -- cgit v1.2.3-54-g00ecf