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
|
---
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: 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")}} 속성을 2^32와 같거나 이보다 긴 값으로 설정했기 때문이다.</li>
</ul>
<p><code>Array와 ArrayBuffer의 길이에 제한을 둔 이유는, Array나 ArrayBuffer의 length 속성은 사인되지 않은(unsigned) 32 비트 정수로 반영되기 때문이다.</code> 즉 <code>Array나 ArrayBuffer는 오직 0 ~ </code>2^32-1 사이의 값만을 저장할 수 있다.</p>
<p>Array의 length로 해석되는 첫번째 argument로서 문자열 표기를 통해 contructor를 사용하여 Array를 생성할 수 있다.</p>
<p>다른 방법으로는, length 속성을 설정하기 전에 length의 길이에 제한을 두거나, constructor의 aurgment로서 사용할 수 있다.</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 is the hexadecimal notation for 2^32 - 1
// which can also be written as (-1 >>> 0)
</pre>
<h2 id="sect1"> </h2>
<ul>
<li>{{jsxref("Array")}}</li>
<li>{{jsxref("Array.length")}}</li>
<li>{{jsxref("ArrayBuffer")}}</li>
</ul>
|