1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
---
title: 'RangeError: invalid array length'
slug: Web/JavaScript/Reference/Errors/Invalid_array_length
translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length
---
<div>{{jsSidebar("Errors")}}</div>
<h2 id="訊息">訊息</h2>
<pre class="syntaxbox">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)
</pre>
<h2 id="錯誤類型">錯誤類型</h2>
<p>{{jsxref("RangeError")}}</p>
<h2 id="哪裡錯了">哪裡錯了?</h2>
<p>一個無效的陣列長度可能發生於以下幾種情形:</p>
<ul>
<li>建立了一個長度為負或大於等於2^32的 {{jsxref("Array")}} 或 {{jsxref("ArrayBuffer")}} </li>
<li>將 {{jsxref("Array.length")}} 屬性設為負值或大於等於 2^32</li>
</ul>
<p>為什麼 <code>Array</code> 和 <code>ArrayBuffer</code> 的長度有限? <code>Array</code> 和 <code>ArrayBuffer</code> 的屬性以一個32位元的非負整數表使,因此僅能儲存 0 到 2^32 - 1 的數值。</p>
<p>If you are creating an <code>Array</code>, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the <code>Array</code>.</p>
<p>Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.</p>
<h2 id="示例">示例</h2>
<h3 id="無效的案例">無效的案例</h3>
<pre class="brush: js example-bad">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
</pre>
<h3 id="有效的案例">有效的案例</h3>
<pre class="brush: js example-good">[ 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)
</pre>
<h2 id="參見">參見</h2>
<ul>
<li>{{jsxref("Array")}}</li>
<li>{{jsxref("Array.length")}}</li>
<li>{{jsxref("ArrayBuffer")}}</li>
</ul>
|