From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../errors/invalid_array_length/index.html | 78 ++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html (limited to 'files/pt-br/web/javascript/reference/errors/invalid_array_length') diff --git a/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html b/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..fc520f9bea --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,78 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - Errors + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

Tipo de erro

+ +

{{jsxref("RangeError")}}

+ +

O que houve de errado?

+ +

Um comprimento inválido de array pode aparecer nas seguintes situações:

+ + + +

Porque Array e ArrayBuffer tem um comprimento limitado? A propriedade length de um Array ou um ArrayBuffer é representado por um inteiro 32-bit unsigned, que pode apenas armazenar valores que estão no intervalo de 0 a 232-1.

+ +

Se você está criando um Array, utilizando o construtor, você provavelmente quer usar a notação literal, onde o primeiro argumento é interpretado como o comprimento do Array.

+ +

Ao contrário, você poderia querer travar o comprimento antes de ajustar a propriedade do comprimento, ou utilizá-lo com um argumento do construtor.

+ +

Exemplos

+ +

Casos inválidos

+ +
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;         // define -1 à propriedade length
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // define 2^32 à propriedade length
+
+ +

Casos válidos

+ +
[ 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 é a notação hexadecimal de 2^32 - 1
+// que também pode ser escrito como (-1 >>> 0)
+
+ +

Veja também

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