Array.prototype.map()

Array 实例的 map() 方法创建一个新数组,其中填充了对调用数组中每个元素调用所提供函数的结果。

¥The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.

Try it

语法

¥Syntax

js
map(callbackFn)
map(callbackFn, thisArg)

参数

¥Parameters

callbackFn

对数组中的每个元素执行的函数。其返回值作为单个元素添加到新数组中。使用以下参数调用该函数:

element

数组中当前正在处理的元素。

index

数组中当前正在处理的元素的索引。

array

调用了数组 map()

thisArg Optional

执行 callbackFn 时用作 this 的值。参见 迭代法

返回值

¥Return value

一个新数组,其中每个元素都是回调函数的结果。

¥A new array with each element being the result of the callback function.

描述

¥Description

map() 方法是 迭代法 方法。它为数组中的每个元素调用一次提供的 callbackFn 函数,并根据结果构造一个新数组。请阅读 迭代法 部分,了解有关这些方法一般如何工作的更多信息。

¥The map() method is an iterative method. It calls a provided callbackFn function once for each element in an array and constructs a new array from the results. Read the iterative methods section for more information about how these methods work in general.

callbackFn 仅针对已赋值的数组索引调用。稀疏数组 中的空槽不会调用它。

¥callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

map() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The map() method is generic. It only expects the this value to have a length property and integer-keyed properties.

由于 map 构建了一个新数组,因此在不使用返回数组的情况下调用它是一种反模式;请使用 forEachfor...of 代替。

¥Since map builds a new array, calling it without using the returned array is an anti-pattern; use forEach or for...of instead.

示例

¥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.

js
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));

// roots is now     [1, 2, 3]
// numbers is still [1, 4, 9]

使用 map 重新格式化数组中的对象

¥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.

js
const kvArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];

const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));

console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
//   { key: 1, value: 10 },
//   { key: 2, value: 20 },
//   { key: 3, value: 30 }
// ]

将 parseInt() 与 map() 一起使用

¥Using parseInt() with map()

通常使用带有一个参数(正在遍历的元素)的回调。某些函数通常也与一个参数一起使用,即使它们采用其他可选参数。这些习惯可能会导致令人困惑的行为。考虑:

¥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:

js
["1", "2", "3"].map(parseInt);

虽然人们可能期望 [1, 2, 3],但实际结果是 [1, NaN, NaN]

¥While one might expect [1, 2, 3], the actual result is [1, NaN, NaN].

parseInt 通常与一个参数一起使用,但也需要两个参数。第一个是表达式,第二个是回调函数的基数,Array.prototype.map 传递 3 个参数:元素、索引和数组。第三个参数被 parseInt 忽略 - 但第二个参数不会!这就是可能造成混乱的根源。

¥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, and 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:

js
/* 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

为了解决这个问题,定义另一个只接受一个参数的函数:

¥To solve this, define another function that only takes one argument:

js
["1", "2", "3"].map((str) => parseInt(str, 10)); // [1, 2, 3]

你还可以使用 Number 函数,它只接受一个参数:

¥You can also use the Number function, which only takes one argument:

js
["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, 10)); // [1, 2, 3]

有关更多讨论,请参阅 Allen Wirfs-Brock 的 JavaScript 可选参数危险

¥See A JavaScript optional argument hazard by Allen Wirfs-Brock for more discussions.

映射数组包含未定义

¥Mapped array contains undefined

当返回 undefined 或不返回任何内容时,结果数组包含 undefined。如果你想删除元素,请链接 filter() 方法,或使用 flatMap() 方法并返回一个空数组来表示删除。

¥When undefined or nothing is returned, the resulting array contains undefined. If you want to delete the element instead, chain a filter() method, or use the flatMap() method and return an empty array to signify deletion.

js
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((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]

副作用映射

¥Side-effectful mapping

回调可能会产生副作用。

¥The callback can have side effects.

js
const cart = [5, 15, 25];
let total = 0;
const withTax = cart.map((cost) => {
  total += cost;
  return cost * 1.2;
});
console.log(withTax); // [6, 18, 30]
console.log(total); // 45

不建议这样做,因为复制方法最好与纯函数一起使用。在这种情况下,我们可以选择对数组进行两次迭代。

¥This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.

js
const cart = [5, 15, 25];
const total = cart.reduce((acc, cost) => acc + cost, 0);
const withTax = cart.map((cost) => cost * 1.2);

有时这种模式会走向极端,map() 所做的唯一有用的事情就是引起副作用。

¥Sometimes this pattern goes to its extreme and the only useful thing that map() does is causing side effects.

js
const products = [
  { name: "sports car" },
  { name: "laptop" },
  { name: "phone" },
];

products.map((product) => {
  product.price = 100;
});

如前所述,这是一种反模式。如果不使用 map() 的返回值,请改用 forEach()for...of 循环。

¥As mentioned previously, this is an anti-pattern. If you don't use the return value of map(), use forEach() or a for...of loop instead.

js
products.forEach((product) => {
  product.price = 100;
});

或者,如果你想创建一个新数组:

¥Or, if you want to create a new array instead:

js
const productsWithPrice = products.map((product) => {
  return { ...product, price: 100 };
});

使用 callbackFn 的第三个参数

¥Using the third argument of callbackFn

如果你想访问数组中的另一个元素,特别是当你没有引用该数组的现有变量时,array 参数非常有用。以下示例首先使用 filter() 提取正值,然后使用 map() 创建一个新数组,其中每个元素都是其邻居元素及其自身的平均值。

¥The array argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter() to extract the positive values and then uses map() to create a new array where each element is the average of its neighbors and itself.

js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const averaged = numbers
  .filter((num) => num > 0)
  .map((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    const prev = arr[idx - 1];
    const next = arr[idx + 1];
    let count = 1;
    let total = num;
    if (prev !== undefined) {
      count++;
      total += prev;
    }
    if (next !== undefined) {
      count++;
      total += next;
    }
    const average = total / count;
    // Keep two decimal places
    return Math.round(average * 100) / 100;
  });
console.log(averaged); // [2, 2.67, 2, 3.33, 5, 5.33, 5.67, 4]

array 参数不是正在构建的数组 - 无法从回调函数访问正在构建的数组。

¥The array argument is not the array that is being built — there is no way to access the array being built from the callback function.

在稀疏数组上使用 map()

¥Using map() on sparse arrays

稀疏数组在 map() 之后仍然保持稀疏。空槽的索引在返回的数组中仍然为空,并且不会对它们调用回调函数。

¥A sparse array remains sparse after map(). The indices of empty slots are still empty in the returned array, and the callback function won't be called on them.

js
console.log(
  [1, , 3].map((x, index) => {
    console.log(`Visit ${index}`);
    return x * 2;
  }),
);
// Visit 0
// Visit 2
// [2, empty, 6]

在非数组对象上调用 map()

¥Calling map() on non-array objects

map() 方法读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

¥The map() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by map() since length is 3
};
console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2));
// [ 4, 9, 16 ]

此示例演示如何迭代 querySelectorAll 收集的对象集合。这是因为 querySelectorAll 返回一个 NodeList (它是对象的集合)。在本例中,我们返回屏幕上所有选定的 option' 值:

¥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 options' values on the screen:

js
const elems = document.querySelectorAll("select option:checked");
const values = Array.prototype.map.call(elems, ({ value }) => value);

还可以使用 Array.from()elems 转换为数组,然后访问 map() 方法。

¥You can also use Array.from() to transform elems to an array, and then access the map() method.

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.map

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看