O método map()
cria uma nova array preenchida com os resultados da chamada de uma função fornecida em cada elemento da matriz de chamada.
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 https://github.com/mdn/interactive-examples and send us a pull request.
Sintaxe
let new_array = arr.map(function callback( currentValue[, index[, array]]) { // retorna novo elemento para new_array }[, thisArg])
Parameteros
callback
-
Função que é chamada para cada elemento de
arr
. Cada vez que a funçãocallback
é executada, o valor devolvido é acrescentado anew_array
.A função
callback
aceita os seguintes argumentos:currentValue
- O elemento da matriz a ser processado.
index
Optional- O indice do elemento da matriz a ser processado.
array
Optional- A matriz em que a função
map
foi chamada.
thisArg
Optional- Valor para usar como
this
ao executar a funçãocallback
.
Valor de retorno
Uma nova matriz em que cada elemento é um resultado da função callback..
Descrição
map
chama a função callback
uma vez por cada elemento na matriz, por ordem, e cria uma matriz com os resultados. callback
é só chamada nos indices da matriz que têm valores (inclusive undefined
).
Não é chamada para elementos que não pertecem à matriz; isto sendo:
- indices que não pertencem pela matriz;
- que foram eliminados; ou
- que nunca tiveram um valor.
Quando não usar map()
Como map
map cira uma nova matriz, é um anti-pattern usar a função quando não se vai usar o valor devolvido; use antes forEach
ou for-of
.
Não deve usar map
se:
- não vai usar o valor devolvido; e/ou
- o
callback
não devolve um valor.
Parameteros em detalhe
callback
é chamada com três argumentos: o valor do elemento, o indice do elemento, e a matriz do objeto a ser mapeado.
Se o parametero thisArg
é fornecido, é usado como o valor de this
na função callback
. Se não, o valor undefined
é usado como o valor de this
. O valor de this
no corpo da função callback
é determinado de acordo com as regras habituais para determinar o valor de this numa função.
map
não modifica a matriz em que é chamada (embora a função callback
, se invocada, possa fazê-lo).
A série de elementos processados por map
é definida antes da primeira invocação de callback
. Os elementos que são anexados ao conjunto após a chamada para map
não serão visitados por callback
. Se os elementos existentes da matriz forem alterados, o seu valor como passado para callback
será o valor no momento em que map
os visitar. Os elementos que são apagados após a chamada para map
começa e antes de serem visitados, não são visitados.
Devido ao algoritmo defenido na especificação, se a matriz em que map
é chamada for esparsa, a matriz resultante também o será com os mesmos indices em branco.
Polyfill
map
was added to the ECMA-262 standard in the 5th edition. Therefore, it may not be present in all implementations of the standard.
You can work around this by inserting the following code at the beginning of your scripts, allowing use of map
in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object
, TypeError
, and Array
have their original values and that callback.call
evaluates to the original value of
.Function.prototype.call
// 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;
};
}
Examples
Mapping an array of numbers to an array of square roots
The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
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]
Using map to reformat objects in an array
The following code takes an array of objects and creates a new array containing the newly reformatted objects.
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}]
Mapping an array of numbers using a function containing an argument
The following code shows how map
works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map
loops through the original array.
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]
Using map generically
This example shows how to use map on a String
to get an array of bytes in the ASCII encoding representing the character values:
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]
Using map generically querySelectorAll
This example shows how to iterate through a collection of objects collected by querySelectorAll
. This is because querySelectorAll
returns a NodeList
(which is a collection of objects).
In this case, we return all the selected option
s' values on the screen:
let elems = document.querySelectorAll('select option:checked')
let values = Array.prototype.map.call(elems, function(obj) {
return obj.value
})
An easier way would be the Array.from()
method.
Tricky use case
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.
Consider:
["1", "2", "3"].map(parseInt)
While one might expect [1, 2, 3]
, the actual result is [1, NaN, NaN]
.
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, Array.prototype.map
passes 3 arguments:
- the element
- the index
- the array
The third argument is ignored by parseInt
—but not the second one! This is the source of possible confusion.
Here is a concise example of the iteration steps:
// 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
Then let's talk about solutions.
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]
One alternative output of the map method being called with parseInt
as a parameter runs as follows:
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.
Mapped array contains undefined
When undefined
or nothing is returned:
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]
Especificações
Compatibilidade
BCD tables only load in the browser