aboutsummaryrefslogtreecommitdiff
path: root/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/pt-pt/web/javascript/reference/global_objects/array/map/index.html')
-rw-r--r--files/pt-pt/web/javascript/reference/global_objects/array/map/index.html366
1 files changed, 366 insertions, 0 deletions
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 &gt;&gt;&gt; 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 &gt; 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 &lt; len
+ while (k &lt; 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 =&gt; {
+ 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) -&gt; 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 =&gt; 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 =&gt; 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 &lt; 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>