diff options
Diffstat (limited to 'files/pt-pt/web/javascript/reference/global_objects/array')
10 files changed, 2197 insertions, 0 deletions
diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..237818a04c --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,205 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - JavaScript + - Prototipo + - Referencia + - Vector + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>concat()</strong></code> é usado para concatenar dois ou mais vectores. Este método não altera os vectores existentes, devolvendo ao invés um novo vector.</p> + +<pre class="brush: js">var vec1 = ['a', 'b', 'c']; +var vec2 = ['d', 'e', 'f']; + +var vec3 = vec1.concat(vec2); + +// vec3 é um novo vector [ "a", "b", "c", "d", "e", "f" ]</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">var <var>novo_vector</var> = <var>velho_vector</var>.concat(<var>valor1</var>[, <var>valor2</var>[, ...[, <var>valorN</var>]]])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor<em>N</em></code></dt> + <dd>Vectores e/ou valores a concatenar num novo vector. Veja a descrição detalhada abaixo.</dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Uma nova instância de {{jsxref("Array")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>concat</code> cria um novo vector constituído pelos elementos no vector em que foi chamado, seguidos por ordem por, cada argumento, os elementos desse argumento (se o argumento é um vector), ou o argumento em si (se o argumento não é um vector). Não entra recursivamente em vectores inclusos.</p> + +<p>O método <code>concat</code> não altera <code>this</code> ou qualquer dos vectores fornecidos como argumentos, devolve sim uma cópia superficial (shallow copy) que contém cópias dos mesmos elementos combinados dos vectores originais. Os elementos dos vectores originais são copiados para o novo vector da seguinte forma:</p> + +<ul> + <li>Object references (and not the actual object): <code>concat</code> copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.</li> + <li>Strings, numbers and booleans (not {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, and {{jsxref("Global_Objects/Boolean", "Boolean")}} objects): <code>concat</code> copies the values of strings and numbers into the new array.</li> +</ul> + +<div class="note"> +<p><strong>Note:</strong> Concatenating array(s)/value(s) will leave the originals untouched. Furthermore, any operation on the new array(only if the element is not object reference) will have no effect on the original arrays, and vice versa.</p> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Concatenar_dois_vectores">Concatenar dois vectores</h3> + +<p>O código que se segue concatena dois vectores:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; +var numerico = [1, 2, 3]; + +alfa.concat(numerico); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_três_vectores">Concatenar três vectores</h3> + +<p>O código que se segue concatena três vectores:</p> + +<pre class="brush: js">var num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = [7, 8, 9]; + +var nums = num1.concat(num2, num3); + +console.log(nums); +// resulta em [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="Concatenar_valores_para_um_vector">Concatenar valores para um vector</h3> + +<p>O código que se segue concatena três valores a um vector:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; + +var alfaNumerico = alfa.concat(1, [2, 3]); + +console.log(alphaNumeric); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_vectores_inclusos">Concatenar vectores inclusos</h3> + +<p>O código que se segue concatena vectores inclusos e demonstra retenção de referências:</p> + +<pre class="brush: js">var num1 = [[1]]; +var num2 = [2, [3]]; + +var nums = num1.concat(num2); + +console.log(nums); +// resulta em [[1], 2, [3]] + +// modificar o primeiro elemento de num1 +num1[0].push(4); + +console.log(nums); +// resulta em [[1, 4], 2, [3]] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementado no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — adicionar/eliminar elementos no fim do vector</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — adicionar/eliminar elementos no início do vector</li> + <li>{{jsxref("Array.splice", "splice")}} — adicionar e/ou eliminar elementos no local especificado do vector</li> + <li>{{jsxref("String.prototype.concat()")}}</li> + <li>{{jsxref("Symbol.isConcatSpreadable")}} – control flattening.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..3eedeb54a9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,210 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>find()</strong></code> retorna o <strong>valor</strong> do primeiro elemento do array que satisfaça a função de teste fornecida. Caso contrário o valor {{jsxref("undefined")}} é retornado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>Ver também o método {{jsxref("Array.findIndex", "findIndex()")}} , o qual retorna o <strong>index</strong> de um elemento encontrado num array, em alternativa do seu valor.</p> + +<p>É possível obter a posição de um elemento ou verificar a sua existência num array, através da função {{jsxref("Array.prototype.indexOf()")}} ou {{jsxref("Array.prototype.includes()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar em cada elemento do array, utilizando três argumentos: + <dl> + <dt><code>element</code></dt> + <dd>O elemento a ser processado no array.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>O index do elemento a ser processado no array.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>O array no qual o método <code>find</code> foi chamado.</dd> + </dl> + </dd> + <dt><code>thisArg</code> <code>{{Optional_inline}}</code></dt> + <dd>Objeto para usar como <code>this</code> ao executar a <code>callback</code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Um valor do array caso um elemento passe no teste; caso contrário, {{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método<code>find</code> executa a <code>callback</code> uma vez para cada index do array até ser encontrado um no qual a <code>callback</code> retorna o valor true. Caso um elemento seja encontrado, o método <code>find</code> retorna imediatamente o seu valor. Caso contrário, o método <code>find</code> retorna {{jsxref("undefined")}}. A função de <code>callback</code> é invocada para cada index do array do <code>0</code> ao <code>length - 1</code> e é invocada para todos os indexes, não apenas nos que tem valor. Isto pode significar que é menos eficiente para o um array com muitos elementos sem valor (sparse array) do que outros métodos que visitam apenas os elementos com valor.</p> + +<p>A função de <code>callback</code> é invocada com 3 parâmetros: o valor do elemento, o index do elemento, e o Array no qual é executado.</p> + +<p>Se o parâmetro <code>thisArg</code> for disponibilizado ao método <code>find</code>, este será usado como <code>this</code> para cada invocação da <code>callback</code>. Caso contrário, será usado o valor {{jsxref("undefined")}}.</p> + +<p>O método <code>find</code> não altera o array no qual é invocado.</p> + +<p>A quantidade de elementos processados pelo método <code>find</code> é definida antes da invocação da <code>callback</code>. Os elementos adicionados ao array após o método <code>find</code> ter iniciado não serão visitados pela <code>callback</code>. Se um elemento existente e não visitado, for alterado pela <code>callback</code>, o seu valor que foi passado para a <code>callback</code> será o valor a ser avaliado pelo método <code>find</code>; Os elementos eliminados após o inicio do método find também serão visitados.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Encontrar_um_objeto_num_array_através_de_uma_das_suas_propriedades">Encontrar um objeto num array através de uma das suas propriedades</h3> + +<pre class="brush: js">var inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +function isCherries(fruit) { + return fruit.name === 'cherries'; +} + +console.log(inventory.find(isCherries)); +// { name: 'cherries', quantity: 5 }</pre> + +<h3 id="Encontrar_um_número_primo_num_array">Encontrar um número primo num array</h3> + +<p>O seguinte exemplo encontra um elemento no array que seja um número primo (caso não exista, retorna {{jsxref("undefined")}} ).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found +console.log([4, 5, 8, 12].find(isPrime)); // 5 +</pre> + +<p>O seguinte exemplo, apresenta como os elementos não existentes e eliminados são visitados e o seu valor passado para a callback será o seu valor quando visitado.</p> + +<pre class="brush: js">// Declare array with no element at index 2, 3 and 4 +var a = [0,1,,,,5,6]; + +// Shows all indexes, not just those that have been assigned values +a.find(function(value, index) { + console.log('Visited index ' + index + ' with value ' + value); +}); + +// Shows all indexes, including deleted +a.find(function(value, index) { + + // Delete element 5 on first iteration + if (index == 0) { + console.log('Deleting a[5] with value ' + a[5]); + delete a[5]; + } + // Element 5 is still visited even though deleted + console.log('Visited index ' + index + ' with value ' + value); +}); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este método foi adicionado ao <em>ECMAScript 2015 Language Specification </em>e pode não estar disponível em todas as implementações de JavaScript. É possível desenvolver o polyfill do método find com o seguinte código:</p> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + } + }); +} +</pre> + +<p>É melhor não utilizar o polyfill <code>Array.prototype</code> para motores JavaScript obsoletos que não suportem métodos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, uma vez que, não é possível torna-los não-enumeráveis.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Browsers">Compatibilidade de Browsers</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – procurar e obter um index</li> + <li>{{jsxref("Array.prototype.includes()")}} – testar se existe um valor num array</li> + <li>{{jsxref("Array.prototype.filter()")}} – encontrar todos os elementos</li> + <li>{{jsxref("Array.prototype.every()")}} – testar se todos os elementos cumprem o requisito</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..77e1bcc9d9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,328 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>forEach()</strong></code> executa a função que foi fornecida uma vez para cada elemento do vetor (array).</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + +<p class="hidden">A origem deste exemplo interactivo está armazenado num repositório do GitHub. Se queres contribuir para o projecto dos exemplos interactivos, por favor clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e manda-nos um pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>vet</var>.forEach(function <var>callback(presenteValor[, indice[, vetor]]) { + //o teu iterador +}</var>[, <var>argThis</var>]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar para cada elemento, levando três argumentos: + <dl> + <dt><code>presenteValor</code></dt> + <dd>Valor do presente elemento a ser processado do vetor (array).</dd> + <dt><code>indice</code>{{optional_inline}}</dt> + <dd>Índice do presente elemento a ser processado do vetor (array).</dd> + <dt><code>vet</code>{{optional_inline}}</dt> + <dd>O vetor (array) a que o <code>forEach()</code> está a ser aplicado.</dd> + </dl> + </dd> + <dt><code>argThis</code> {{Optional_inline}}</dt> + <dd> + <p>Valor a usar como <code><strong>this</strong></code> (ou seja o <code>Object</code> de referência) quando é executado o <code>callback</code>.</p> + </dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>forEach()</code> executa o <code>callback</code> fornecido uma vez para cada elemento presente no vetor (array) por ordem ascendente. Não é invocado para indices de propriedades que foram apagadas ou que não foram inicializadas (ou seja em sparse arrays).</p> + +<p><code>callback</code> é invocado com <strong>três argumentos</strong>:</p> + +<ul> + <li>o <strong>valor do elemento</strong></li> + <li>o <strong>índice do elemento</strong></li> + <li>o <strong>vetor (array) que está a ser percorrido</strong></li> +</ul> + +<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.</p> + +<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>There is no way to stop or break a <code>forEach()</code> loop other than by throwing an exception. If you need such behavior, the <code>forEach()</code> method is the wrong tool.</p> + +<p>Early termination may be accomplished with:</p> + +<ul> + <li>A simple loop</li> + <li>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> loop</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>The other Array methods: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_Array_Object">Printing the contents of an Array Object</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">var userInfo = [{ + name: "Mayank", + age: 30 +}, { + name: Meha, + age: 26 +}]; + +userInfo.forEach(function(employee) { + console.log(employee.name) +}); +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Notice that index 2 is skipped since there is no item at +// that position in the array. +[2, 5, , 9].forEach(logArrayElements); +// logs: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0; + this.count = 0; +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry; + ++this.count; + }, this); + // ^---- Note +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)); + const propNames = Object.getOwnPropertyNames(obj); + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name); + Object.defineProperty(copy, name, desc); + }); + + return copy; +} + +const obj1 = { a: 1, b: 2 }; +const obj2 = copy(obj1); // obj2 looks like obj1 now +</pre> + +<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat while k < len. + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator. + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c. + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined. + }; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..201d4c9526 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,175 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>includes()</strong></code> determina se um array contém um determinado elemento, devolvendo <code>true</code> ou <code>false</code>. É utilizado o algoritmo sameValueZero para determinar se o elemento especificado foi encontrado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement[</var>, <var>fromIndex]</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>The element to search for.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>The position in this array at which to begin searching for <code>searchElement</code>. A negative value searches from the index of <code>array.length - fromIndex</code> by asc. Defaults to 0.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A {{jsxref("Boolean")}}.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">[1, 2, 3].includes(2); // true +[1, 2, 3].includes(4); // false +[1, 2, 3].includes(3, 3); // false +[1, 2, 3].includes(3, -1); // true +[1, 2, NaN].includes(NaN); // true +</pre> + +<h3 id="fromIndex_is_greater_than_or_equal_to_the_array_length"><code>fromIndex</code> is greater than or equal to the array length</h3> + +<p>If <code>fromIndex</code> is greater than or equal to the length of the array, <code>false</code> is returned. The array will not be searched.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="Computed_index_is_less_than_0">Computed index is less than 0</h3> + +<p>If <code>fromIndex</code> is negative, the computed index is calculated to be used as a position in the array at which to begin searching for <code>searchElement</code>. If the computed index is less than 0, the entire array will be searched.</p> + +<pre class="brush: js">// array length is 3 +// fromIndex is -100 +// computed index is 3 + (-100) = -97 + +var arr = ['a', 'b', 'c']; + +arr.includes('a', -100); // true +arr.includes('b', -100); // true +arr.includes('c', -100); // true</pre> + +<h3 id="includes()_used_as_a_generic_method"><code>includes()</code> used as a generic method</h3> + +<p><code>includes()</code> method is intentionally generic. It does not require <code>this</code> value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates <code>includes()</code> method called on the function's <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> object.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.includes +if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + value: function(searchElement, fromIndex) { + + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If len is 0, return false. + if (len === 0) { + return false; + } + + // 4. Let n be ? ToInteger(fromIndex). + // (If fromIndex is undefined, this step produces the value 0.) + var n = fromIndex | 0; + + // 5. If n ≥ 0, then + // a. Let k be n. + // 6. Else n < 0, + // a. Let k be len + n. + // b. If k < 0, let k be 0. + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + function sameValueZero(x, y) { + return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); + } + + // 7. Repeat, while k < len + while (k < len) { + // a. Let elementK be the result of ? Get(O, ! ToString(k)). + // b. If SameValueZero(searchElement, elementK) is true, return true. + if (sameValueZero(o[k], searchElement)) { + return true; + } + // c. Increase k by 1. + k++; + } + + // 8. Return false + return false; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..5f26f41549 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,440 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Class + - Exemplo + - Global Objects + - JavaScript + - Referencia + - 'l10n:priority' +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>A classe de JavaScript <strong><code>Array</code></strong> é um objecto global que é utilizado na construção de matrizes; que são objectos de alto nível, semelhantes a listas.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Arrays são objectos em forma de lista, cujo protótipo tem métodos para realizar operações de travessia e mutação. Nem o comprimento de uma array JavaScript nem os tipos dos seus elementos são fixos. Uma vez que o comprimento de uma array pode mudar a qualquer momento, e os dados podem ser armazenados em locais não contíguos da array, não é garantido que uma array JavaScript seja densa; isto depende de como o programador opta por usá-las. Em geral, estas são características convenientes; mas se estas características não forem desejáveis para seu uso particular, você pode considerar o uso de arrays tipadas.</p> + +<p>Uma array não pode utilizar strings como índices de elementos (como num {{InterWiki("wikipedia", "Vetor_associativo", "array associativa")}}), deve utilizar números inteiros. A definição ou acesso através de não-inteiros usando notação de parênteses (ou notação de pontos) não definirá ou recuperará um elemento da própria lista da array, mas definirá ou acessará uma variável associada à <a href="pt-PT/docs/Web/JavaScript/Estruturas_de_dados#Objetos">coleção de propriedades dessa array</a>. As propriedades da array e a lista de elementos do mesmo são separadas, e as operações de translação e mutação da array não podem ser aplicadas a essas propriedades com nome.</p> + +<p><strong>Criar uma Array</strong></p> + +<pre class="brush: js notranslate">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>Aceder (através de índice) item<span class="original-content"> da </span>Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>Loop over an Array</strong></p> + +<pre class="brush: js notranslate">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>Adicionar um item ao fim da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>Remover um item do fim da Array</strong></p> + +<pre class="brush: js notranslate">var last = fruits.pop(); // remove Orange (from the end) +// ["Apple", "Banana"]; +</pre> + +<p><strong>Remover um item do início da Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits.shift(); // remove Apple from the front +// ["Banana"]; +</pre> + +<p><strong>Ad</strong><strong>icionar um item ao início da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.unshift('Strawberry') // add to the front +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>Encontrar o índice dum item na Array</strong></p> + +<pre class="brush: js notranslate">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>Remover um item pela posição do índice</strong></p> + +<pre class="brush: js notranslate">var removedItem = fruits.splice(pos, 1); // this is how to remove an item + +// ["Strawberry", "Mango"]</pre> + +<p><strong>Remover items pela posição do índice</strong></p> + +<pre class="brush: js notranslate">var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; +console.log(vegetables); +// ["Cabbage", "Turnip", "Radish", "Carrot"] + +var pos = 1, n = 2; + +var removedItems = vegetables.splice(pos, n); +// this is how to remove items, n defines the number of items to be removed, +// from that position(pos) onward to the end of array. + +console.log(vegetables); +// ["Cabbage", "Carrot"] (the original array is changed) + +console.log(removedItems); +// ["Turnip", "Radish"]</pre> + +<p><strong>Copiar uma Array</strong></p> + +<pre class="brush: js notranslate">var shallowCopy = fruits.slice(); // this is how to make a copy +// ["Strawberry"] +</pre> + +<h3 id="Como_aceder_a_elementos_da_array">Como aceder a elementos da array</h3> + +<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.</p> + +<pre class="brush: js notranslate">var arr = ['this is the first element', 'this is the second element']; +console.log(arr[0]); // logs 'this is the first element' +console.log(arr[1]); // logs 'this is the second element' +console.log(arr[arr.length - 1]); // logs 'this is the second element' +</pre> + +<p>Array elements are object properties in the same way that <code>toString</code> is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:</p> + +<pre class="brush: js notranslate">console.log(arr.0); // a syntax error +</pre> + +<p>There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> + +<pre class="brush: js notranslate">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // a syntax error +console.log(years[0]); // works properly +</pre> + +<pre class="brush: js notranslate">renderer.3d.setTexture(model, 'character.png'); // a syntax error +renderer['3d'].setTexture(model, 'character.png'); // works properly +</pre> + +<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is for this reason that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> + +<pre class="brush: js notranslate">console.log(years['2'] != years['02']); +</pre> + +<p>Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):</p> + +<pre class="brush: js notranslate">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['var']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> + +<p>A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.</p> + +<pre class="brush: js notranslate">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:</p> + +<pre class="brush: js notranslate">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>Increasing the {{jsxref("Array.length", "length")}}.</p> + +<pre class="brush: js notranslate">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> + +<pre class="brush: js notranslate">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>This is explained further on the {{jsxref("Array.length")}} page.</p> + +<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> + +<p>The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:</p> + +<pre class="brush: js notranslate">// Match one d followed by one or more b's followed by one d +// Remember matched b's and the following d +// Ignore case + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>The properties and elements returned from this match are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Property/Element</td> + <td class="header">Description</td> + <td class="header">Example</td> + </tr> + <tr> + <td><code>input</code></td> + <td>A read-only property that reflects the original string against which the regular expression was matched.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>A read-only property that is the zero-based index of the match in the string.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>A read-only element that specifies the last matched characters.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Returns true if a variable is an array, if not false.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<div class="warning"> +<p><strong>Array generics are non-standard, deprecated and will get removed in the near future</strong>. </p> +</div> + +<p>Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js notranslate">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js notranslate">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> + +<p>These are <strong>not</strong> part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:</p> + +<pre class="brush: js notranslate">if (Array.from(str).every(isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_an_array">Creating an array</h3> + +<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> + +<pre class="brush: js notranslate">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 id="Creating_a_two-dimensional_array">Creating a two-dimensional array</h3> + +<p>The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.</p> + +<pre class="brush: js notranslate">var board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ]; + +console.log(board.join('\n') + '\n\n'); + +// Move King's Pawn forward 2 +board[4][4] = board[6][4]; +board[6][4] = ' '; +console.log(board.join('\n')); +</pre> + +<p>Here is the output:</p> + +<pre class="eval notranslate">R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , , , , , + , , , , , , , +p,p,p,p,p,p,p,p +r,n,b,q,k,b,n,r + +R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , ,p, , , + , , , , , , , +p,p,p,p, ,p,p,p +r,n,b,q,k,b,n,r +</pre> + +<h3 id="Using_an_array_to_tabulate_a_set_of_values">Using an array to tabulate a set of values</h3> + +<pre class="brush: js notranslate">values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</pre> + +<p>Results in</p> + +<pre class="eval notranslate">0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162</pre> + +<p>(First column is the (index))</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Navegadores">Compatibilidade de Navegadores</h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, por favor consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..aec6f34cc2 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,90 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - JavaScript + - Prototipo + - Referencia + - Vector + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>join()</strong></code> cria e devolve uma <em>string</em> ao concatenar todos os elementos numa <em>array</em> (ou <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">objeto como um vetor / matriz</a>) numa cadeia separada por vírgulas ou outro separador especificado. Se a <em>array</em> tem um só item, esse item é devolvido sem o uso do separador.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>vec</var>.join([<var>separador</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>separador</code> {{optional_inline}}</dt> + <dd>Especifica uma <em>string</em> (cadeia de caracteres) para separar cada elemento do vetor. O separador é convertido em cadeia se for necessário. Se for omitido, os elementos serão separados por virgulas (","). Se <code>separador</code> é uma cadeia vazia, todos os elementos são unidos sem qualquer caráter entre eles.</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma cadeia (de caracteres) com todos os elementos do vetor unidos. Se <code><em>vec</em>.length</code> é <code>0</code>, é devolvida uma cadeia vazia.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>As conversões de todos os elementos do vetor para cadeias (de caracteres) são unidas numa única cadeia.</p> + +<p>Caso algum elemento seja <code>undefined</code>, <code>null</code> ou um vetor vazio <code>[]</code>, este será convertido numa cadeia vazia.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Juntar_um_vetor_de_quatro_formas_diferentes">Juntar um vetor de quatro formas diferentes</h3> + +<p>O exemplo que se segue cria um vetor, <code>a</code>, com três elementos, depois disso une o vetor quatro vezes: usando o separador predefinido, uma vírgula e um espaço, o símbolo mais, e finalmente uma cadeia (de caracteres) vazia.</p> + +<pre class="brush: js notranslate">var a = ['Vento', 'Chuva', 'Fogo']; +a.join(); // 'Vento,Chuva,Fogo' +a.join(', '); // 'Vento, Chuva, Fogo' +a.join(' + '); // 'Vento + Chuva + Fogo' +a.join(''); // 'VentoChuvaFogo'</pre> + +<h3 id="Juntar_um_objeto_como_vetor">Juntar um objeto como vetor</h3> + +<p>O seguinte exemplo junta um objeto como vetor (<code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>), ao chamar {{jsxref("Function.prototype.call")}} no <code>Array.prototype.join</code>.</p> + +<pre class="brush: js notranslate">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +// valor devolvido: "1,a,true" +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..12910ebc2a --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,366 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referencia + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">O método <code><strong>map()</strong></code> <strong>cria uma nova array</strong> preenchida com os resultados da chamada de uma função fornecida em cada elemento da matriz de chamada.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">let <var>new_array</var> = <var>arr</var>.map(function <var>callback</var>( <var>currentValue</var>[, <var>index</var>[, <var>array</var>]]) { + // retorna novo elemento para new_array +}[, <var>thisArg</var>]) +</pre> + +<h3 id="Parameteros">Parameteros</h3> + +<dl> + <dt><code><var>callback</var></code></dt> + <dd> + <p>Função que é chamada para cada elemento de <code>arr</code>. Cada vez que a função <code>callback</code> é executada, o valor devolvido é acrescentado a <code>new_array</code>.</p> + + <p>A função <code><var>callback</var></code> aceita os seguintes argumentos:</p> + + <dl> + <dt><code><var>currentValue</var></code></dt> + <dd>O elemento da matriz a ser processado.</dd> + <dt><code><var>index</var></code>{{optional_inline}}</dt> + <dd>O indice do elemento da matriz a ser processado.</dd> + <dt><code><var>array</var></code>{{optional_inline}}</dt> + <dd>A matriz em que a função <code>map</code> foi chamada.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>Valor para usar como <code>this</code> ao executar a função <code><var>callback</var></code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Uma nova matriz em que cada elemento é um resultado da função callback..</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>map</code> chama a função <code><var>callback</var></code> <strong>uma vez por cada elemento</strong> na matriz, por ordem, e cria uma matriz com os resultados. <code><var>callback</var></code> é só chamada nos indices da matriz que têm valores (inclusive {{jsxref("undefined")}}).</p> + +<p>Não é chamada para elementos que não pertecem à matriz; isto sendo:</p> + +<ul> + <li>indices que não pertencem pela matriz;</li> + <li>que foram eliminados; ou</li> + <li>que nunca tiveram um valor.</li> +</ul> + +<h3 id="Quando_não_usar_map">Quando não usar map()</h3> + +<p>Como <code>map</code> map cira uma nova matriz, é um <em>anti-pattern</em> usar a função quando não se vai usar o valor devolvido; use antes {{jsxref("Array/forEach", "forEach")}} ou {{jsxref("for...of", "for-of")}}.</p> + +<p>Não deve usar <code>map</code> se:</p> + +<ul> + <li>não vai usar o valor devolvido; e/ou</li> + <li>o <code>callback</code> não devolve um valor.</li> +</ul> + +<h3 id="Parameteros_em_detalhe">Parameteros em detalhe</h3> + +<p><code><var>callback</var></code> é chamada com três argumentos: o valor do elemento, o indice do elemento, e a matriz do objeto a ser mapeado.</p> + +<p>Se o parametero <code>thisArg</code> é fornecido, é usado como o valor de <code>this</code> na função <em><code>callback</code></em>. Se não, o valor {{jsxref("undefined")}} é usado como o valor de <code>this</code>. O valor de <code>this</code> no corpo da função <code><var>callback</var></code> é determinado de acordo com <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">as regras habituais para determinar o valor de this numa função</a>.</p> + +<p><code>map</code> não modifica a matriz em que é chamada (embora a função <em><code>callback</code></em>, se invocada, possa fazê-lo).</p> + +<p>A série de elementos processados por <code>map</code> é definida antes da primeira invocação de <em><code>callback</code></em>. Os elementos que são anexados ao conjunto após a chamada para <code>map</code> não serão visitados por <code><em>callback</em></code>. Se os elementos existentes da matriz forem alterados, o seu valor como passado para <em><code>callback</code></em> será o valor no momento em que <code>map</code> os visitar. Os elementos que são apagados após a chamada para <code>map</code> começa e antes de serem visitados, não são visitados.</p> + +<p>Devido ao algoritmo defenido na especificação, se a matriz em que <code>map</code> é chamada for esparsa, a matriz resultante também o será com os mesmos indices em branco.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map</code> was added to the ECMA-262 standard in the 5th edition. Therefore, it may not be present in all implementations of the standard.</p> + +<p>You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p> + +<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.19 +// Reference: http://es5.github.io/#x15.4.4.19 +if (!Array.prototype.map) { + + Array.prototype.map = function(callback/*, thisArg*/) { + + var T, A, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Mapping_an_array_of_numbers_to_an_array_of_square_roots">Mapping an array of numbers to an array of square roots</h3> + +<p>The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.</p> + +<pre class="brush: js notranslate">let numbers = [1, 4, 9] +let roots = numbers.map(function(num) { + return Math.sqrt(num) +}) +// roots is now [1, 2, 3] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_to_reformat_objects_in_an_array">Using map to reformat objects in an array</h3> + +<p>The following code takes an array of objects and creates a new array containing the newly reformatted objects.</p> + +<pre class="brush: js notranslate">let kvArray = [{key: 1, value: 10}, + {key: 2, value: 20}, + {key: 3, value: 30}] + +let reformattedArray = kvArray.map(obj => { + let rObj = {} + rObj[obj.key] = obj.value + return rObj +}) +// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}], + +// kvArray is still: +// [{key: 1, value: 10}, +// {key: 2, value: 20}, +// {key: 3, value: 30}] +</pre> + +<h3 id="Mapping_an_array_of_numbers_using_a_function_containing_an_argument">Mapping an array of numbers using a function containing an argument</h3> + +<p>The following code shows how <code>map</code> works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as <code>map</code> loops through the original array.</p> + +<pre class="brush: js notranslate">let numbers = [1, 4, 9] +let doubles = numbers.map(function(num) { + return num * 2 +}) + +// doubles is now [2, 8, 18] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_generically">Using map generically</h3> + +<p>This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:</p> + +<pre class="brush: js notranslate">let map = Array.prototype.map +let a = map.call('Hello World', function(x) { + return x.charCodeAt(0) +}) +// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="Using_map_generically_querySelectorAll">Using map generically querySelectorAll</h3> + +<p>This example shows how to iterate through a collection of objects collected by <code>querySelectorAll</code>. This is because <code>querySelectorAll</code> returns a <code>NodeList</code> (which is a collection of objects).</p> + +<p>In this case, we return all the selected <code>option</code>s' values on the screen:</p> + +<pre class="brush: js notranslate">let elems = document.querySelectorAll('select option:checked') +let values = Array.prototype.map.call(elems, function(obj) { + return obj.value +}) +</pre> + +<p>An easier way would be the {{jsxref("Array.from()")}} method.</p> + +<h3 id="Tricky_use_case">Tricky use case</h3> + +<p>(<a href="http://www.wirfs-brock.com/allen/posts/166">inspired by this blog post</a>)</p> + +<p>It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.</p> + +<p>Consider:</p> + +<pre class="brush: js notranslate">["1", "2", "3"].map(parseInt)</pre> + +<p>While one might expect <code>[1, 2, 3]</code>, the actual result is <code>[1, NaN, NaN]</code>.</p> + +<p>{{jsxref("parseInt")}} is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, <code>Array.prototype.map</code> passes 3 arguments:</p> + +<ul> + <li>the element</li> + <li>the index</li> + <li>the array</li> +</ul> + +<p>The third argument is ignored by {{jsxref("parseInt")}}—but <em>not</em> the second one! This is the source of possible confusion.</p> + +<p>Here is a concise example of the iteration steps:</p> + +<pre class="brush: js notranslate">// parseInt(string, radix) -> map(parseInt(value, index)) +/* first iteration (index is 0): */ parseInt("1", 0) // 1 +/* second iteration (index is 1): */ parseInt("2", 1) // NaN +/* third iteration (index is 2): */ parseInt("3", 2) // NaN +</pre> + +<p>Then let's talk about solutions.</p> + +<pre class="brush: js notranslate">function returnInt(element) { + return parseInt(element, 10) +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// Actual result is an array of numbers (as expected) + +// Same as above, but using the concise arrow function syntax +['1', '2', '3'].map( str => parseInt(str) ) + +// A simpler way to achieve the above, while avoiding the "gotcha": +['1', '2', '3'].map(Number) // [1, 2, 3] + +// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: +['1.1', '2.2e2', '3e300'].map(Number) // [1.1, 220, 3e+300] + +// For comparison, if we use parseInt() on the array above: +['1.1', '2.2e2', '3e300'].map( str => parseInt(str) ) // [1, 2, 3] +</pre> + +<p>One alternative output of the map method being called with {{jsxref("parseInt")}} as a parameter runs as follows:</p> + +<pre class="brush: js notranslate">let xs = ['10', '10', '10'] + +xs = xs.map(parseInt) + +console.log(xs) +// Actual result of 10,NaN,2 may be unexpected based on the above description.</pre> + +<h3 id="Mapped_array_contains_undefined">Mapped array contains undefined</h3> + +<p>When {{jsxref("undefined")}} or nothing is returned:</p> + +<pre class="brush: js notranslate">let numbers = [1, 2, 3, 4] +let filteredNumbers = numbers.map(function(num, index) { + if (index < 3) { + return num + } +}) +// index goes from 0, so the filterNumbers are 1,2,3 and undefined. +// filteredNumbers is [1, 2, 3, undefined] +// numbers is still [1, 2, 3, 4] + +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..440ea3e6ee --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,96 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - JavaScript + - Lista + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>pop()</strong></code> remove o último elemento de um array e retorna esse elemento. Este método altera o tamanho do array.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>O elemento removido do array; {{jsxref("undefined")}} se o array estiver vazio.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>pop</code> remove o último elemento de um array e retorna esse elemento para a função que o chamou.</p> + +<p><code>pop</code> é um método intencionalmente genérico; este método pode ser {{jsxref("Function.call", "called", "", 1)}} ou {{jsxref("Function.apply", "applied", "", 1)}} para objectos parecidos com arrays. Objectos que não contenham a propriedade <code>length</code> (tamanho) que reflete o último elemento numa lista de consecutivas propriedades numéricas zero-based, pode não se comportar de maneira significativa.</p> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Se o método </span></font>pop()</code> for chamado num array vazio este retorna {{jsxref("undefined")}}.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Remover_o_último_elemento_de_um_array">Remover o último elemento de um array</h3> + +<p>O seguinte exemplo cria um array <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">peixes</span></font> que contêm quatro elementos, e depois remove o último elemento.</p> + +<pre class="brush: js">var peixes = ['anjo', 'palhaço', 'mandarim', 'esturjão']; + +var popped = peixes.pop(); + +console.log(peixes); // ['anjo', 'palhaço', 'mandarim'] + +console.log(popped); // 'esturjão'</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementada no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="Ver_também">Ver também </h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..a442018c61 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,133 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>reverse()</strong></code> inverte um vector (<code>Array</code>). O primeiro elemento torna-se o último, e o último elemento torna-se o primeiro.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>a</var>.reverse()</pre> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>O vector (<code>Array</code>) invertido.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>reverse</code> transpõe os elementos do vector que o chamou, mudando o vector, e devolvendo uma referência para o vector.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Invertendo_os_elementos_num_vector">Invertendo os elementos num vector</h3> + +<p>O exemplo que se segue cria um vector <code>a</code>, que contém três elementos, e depois o inverte. A chamada a <code>reverse()</code> devolve uma referência para o vector invertido <code>a</code>.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +var invertido = a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +console.log(invertido); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..48820a1ff7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,154 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>slice()</strong></code> devolve uma cópia rasa (é feita uma cópia dos <em>pointers</em> se for um objeto) de uma parte de uma matriz num novo objeto de <code>array</code> selecionado do <code>start</code> (início incluído) ao <code>end</code> (fim excluído) onde o <code>start</code> e o <code>end</code> representam o índice de itens dessa matriz. A matriz original não é modificada.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.slice([<var>start</var>[, <var>end</var>]]) +</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>start</var></code> {{optional_inline}}</dt> + <dd>Indice de base zero, onde coméça a cópia.</dd> + <dd>Um índice negativo pode ser utilizado, indicando um intervalo a partir do fim da sequência. <code>slice(-2)</code> extrai os dois últimos elementos da sequência.</dd> + <dd>Se <code><var>start</var></code> é undefined, <code>slice</code> coméça a partir do indice <code>0</code>.</dd> + <dd>Se <code><var>start</var></code> é maior que o último índice da sequência, uma matriz vazia é devolvida.</dd> + <dt><code><var>end</var></code> {{optional_inline}}</dt> + <dd>Índice antes do qual se deve terminar a extração. <code>slice</code> extrai até o valor de indice <code>end</code>, mas sem incluir <code>end</code>. Por exemplo, <code>slice(1,4)</code> extrai do segundo até ao quarto elemento (elementos indexados 1, 2, e 3).</dd> + <dd>Pode ser utilizado um índice negativo, indicando o último índice a partir do fim da sequência. <code>slice(2,-1)</code> extrai do terceiro até ao penúltimo elemento na sequência.</dd> + <dd>Se <code>end</code> é omisso, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> + <dd>Se <code>end</code> é maior que o comprimento da sequência, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma matriz nova contendo os elementos extraídos.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>slice</code> não altera a matriz original. Devolve uma cópia rasa dos elementos da matriz original. Os elementos da matriz original são copiados para a matriz devolvida como se segue:</p> + +<ul> + <li>Para referências de objectos (e não o objecto real), <code>slice</code> copia as referências de objectos para a nova matriz. Tanto o original como a nova matriz referem-se ao mesmo objecto. Se um objecto referenciado mudar, as mudanças são visíveis tanto para a nova matriz como para a original.</li> + <li>Para strings, números e booleanos (não {{jsxref("String")}}, {{jsxref("Number")}} e {{jsxref("Booleano")}} objetos), <code>slice</code> copia os valores para a nova matriz. Alterações à string, número, ou booleano numa matriz não afetam a outra matriz.</li> +</ul> + +<p>Se um novo elemento é adicionado a qualquer das matrizes, a outra matriz não é afetada.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Devolver_uma_porção_duma_matriz">Devolver uma porção duma matriz</h3> + +<pre class="brush: js notranslate">let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +let citrus = fruits.slice(1, 3) + +// fruits contêm ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus contêm ['Orange','Lemon'] +</pre> + +<h3 id="Usar_slice">Usar <code>slice</code></h3> + +<p>No seguinte exemplo, <code>slice</code> cria uma <em>array</em> (matriz), <code>newCar</code>, a partir de <code>myCar</code>. Ambos incluem uma referência ao objeto <code>myHonda</code>. Quando a propriedade <em>color</em> (cor) de <code>myHonda</code> é mudada para <em>purple</em> (roxo), ambas matrizes refletem a alteração.</p> + +<pre class="brush: js notranslate">// Usando slice, cria newCar a partir de myCar. +let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } } +let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'] +let newCar = myCar.slice(0, 2) + +// Imprime os valors de myCar, newCar, a propriadade +// color de myHonda em ambas arrays. +console.log('myCar = ' + JSON.stringify(myCar)) +console.log('newCar = ' + JSON.stringify(newCar)) +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color) + +// Mude a propriadade color de myHonda. +myHonda.color = 'purple' +console.log('A nova cor de my Honda é ' + myHonda.color) + +// Imprime a propriadade color de myHonda em ambas arrays. +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color) +</pre> + +<p>Este <em>script</em> imprime:</p> + +<pre class="notranslate">myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, + 'cherry condition', 'purchased 1997'] +newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] +myCar[0].color = red +newCar[0].color = red +A nova cor de my Honda é purple +myCar[0].color = purple +newCar[0].color = purple +</pre> + +<h3 id="Objetos_parecidos_com_Array">Objetos parecidos com Array</h3> + +<p>O método <code>slice</code> tembém pode ser chamado para converter objetos / coleções do estilo matriz para um objeto <code>Array</code>. É só preciso {{jsxref("Function.prototype.bind", "<em>bind</em>")}} o método ao objeto. Os {{jsxref("Functions/arguments", "argumentos")}} dentro da função são um exemplo de um "objeto de estilo matriz".</p> + +<pre class="brush: js notranslate">function list() { + return Array.prototype.slice.call(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3] +</pre> + +<p><em>Binding</em> pode ser feito com o método {{jsxref("Function.prototype.call", "call()")}} de {{jsxref("Function.prototype")}} e também pode ser simplificado a usar <code>[].slice.call(arguments)</code> invés de <code>Array.prototype.slice.call</code>.</p> + +<p>Pode ser simplificado a usar {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js notranslate">let unboundSlice = Array.prototype.slice +let slice = Function.prototype.call.bind(unboundSlice) + +function list() { + return slice(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3]</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> |
