JavaScript Array map()

Definition and usage

map() The method creates a new array using the results of calling the function for each array element.

map() The method calls the provided function once for each element in the array in order.

Note:map() Does not execute the function for array elements without values.

Note:map() Does not change the original array.

Instance

Example 1

Return an array of all square roots of the values in the original array:

var numbers = [4, 9, 16, 25];
var x = numbers.map(Math.sqrt);
document.getElementById("demo").innerHTML = x;

亲自试一试

例子 2

将数组中的所有值乘以 10:

var numbers = [65, 44, 12, 4];
var newarray = numbers.map(myFunction)
function myFunction(num) {
  return num * 10;
}
document.getElementById("demo").innerHTML = newarray;;

亲自试一试

例子 3

获取数组中每个人的全名:

var persons = [
  {firstname : "Malcom", lastname: "Reynolds"},
  {firstname : "Kaylee", lastname: "Frye"},
  {firstname : "Jayne", lastname: "Cobb"}
];
function getFullName(item) {
  var fullname = [item.firstname,item.lastname].join(" ");
  return fullname;
}
function myFunction() {
  document.getElementById("demo").innerHTML = persons.map(getFullName);
}

亲自试一试

语法

array.map(function(currentValue, index, arr), thisValue)

参数值

参数 描述
function(currentValue, index, arr) 必需。为数组中的每个元素运行的函数。

函数参数:

参数 描述
currentValue 必需。当前元素的值。
index 可选。当前元素的数组索引。
arr 可选。当前元素所属的数组对象
thisValue

可选。要传递给函数以用作其 "this" 值的值。

如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。

技术细节

返回值: 数组,包含为原始数组中的每个元素调用提供的函数的结果。
JavaScript 版本: ECMAScript 5

浏览器支持

表格中的数字注明了完全支持该方法的首个浏览器版本。

所有浏览器都完全支持 map() 方法:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Stöd 9.0 Stöd Stöd Stöd Stöd

Relaterade sidor

Tutorial:JavaScript-array

Tutorial:JavaScript-array-Const

Tutorial:JavaScript-arraymetoder

Tutorial:JavaScript-sortera-array

Tutorial:JavaScript-arrayiteration