Return a new array with the square root of all element values:
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
Try it Yourself »
Multiply all the values in an array with 10:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
Try it Yourself »
More examples below.
map()
creates a new array from calling a function for every array element.
map()
does not execute the function for empty elements.
map()
does not change the original array.
array.map(
function(currentValue, index, arr), thisValue)
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default value undefined .A value passed to the function to be used as its this value. |
Type | Description |
An array | The results of a function for each array element. |
Get the full name for each person:
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}
Try it Yourself »
map()
is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!