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
75
76
77
78
|
---
title: 'RangeError: invalid array length'
slug: Web/JavaScript/Reference/Errors/Invalid_array_length
tags:
- Array
- JavaScript
- RangeError
- errores
translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length
---
<div>{{jsSidebar("Errors")}}</div>
<h2 id="Mensaje">Mensaje</h2>
<pre class="syntaxbox">RangeError: invalid array length (Firefox)
RangeError: Invalid array length (Chrome)
RangeError: Invalid array buffer length (Chrome)
</pre>
<h2 id="Tipo_de_error">Tipo de error</h2>
<p>{{jsxref("RangeError")}}</p>
<h2 id="¿Cuál_es_el_problema">¿Cuál es el problema?</h2>
<p>Una longitud de array inválida puede presentarse en éstas situaciones:</p>
<ul>
<li>Cuando se crea un {{jsxref("Array")}} o un {{jsxref("ArrayBuffer")}} el cual tiene una longitud negativa o es igual o mayor a 2<sup>32</sup>, o</li>
<li>cuando se define la propiedad {{jsxref("Array.length")}} a un valor el cual es negativo o es igual o mayor a 2<sup>32</sup>.</li>
</ul>
<p>¿Por qué el <code>Array</code> y <code>ArrayBuffer</code> tienen longitud limitada? La propiedad de longitud de un <code>Array</code> o un <code>ArrayBuffer</code> está representada con un entero sin signo de 32 bits, el cual sólo puede almacenar valores que estén en el rango de 0 a 2<sup>32</sup>-1.</p>
<p>Si estás creando un <code>Array</code> usando el constructor, es mejor que utilices la notación literal, ya que el primer argumento es interpretado como la longitud del <code>Array</code>.</p>
<p>De lo contrario, puedes <span class="_Tgc">especificar</span> un mínimo y un máximo para la longitud antes de definir la propiedad de longitud, o puedes usarla como el argumento del constructor.</p>
<h2 id="Ejemplos">Ejemplos</h2>
<h3 id="Casos_inválidos">Casos inválidos</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; // definir la propiedad de longitud a -1
let b = new Array(Math.pow(2, 32) - 1);
b.length = b.length + 1; // definir la propiedad de longitud a 2^32
</pre>
<h3 id="Casos_válidos">Casos válidos</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 es la notación hexadecimal de 2^32 - 1
// el cual también se puede especificar como (-1 >>> 0)
</pre>
<h2 id="Véase_también">Véase también</h2>
<ul>
<li>{{jsxref("Array")}}</li>
<li>{{jsxref("Array.length")}}</li>
<li>{{jsxref("ArrayBuffer")}}</li>
</ul>
|