「这是我参与11月更文挑战的第21天,活动详情查看:2021最后一次更文挑战」
本文将探讨JavaScript Array的Array.forEach()和Array.map()方法之间的区别。
1.返回值
forEach()方法返回undefined而map()返回一个包含转换了的元素的新数组。下面用这两个方法得到由原数组中每个元素的平方组成的新数组。
const numbers = [1, 2, 3, 4, 5];
// 使用 forEach()
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));
// 使用 map()
const squareUsingMap = numbers.map(x => x*x);
console.log(squareUsingForEach); // [1, 4, 9, 16, 25]
console.log(squareUsingMap); // [1, 4, 9, 16, 25]
由于 forEach() 返回 undefined,我们需要传递一个空数组来创建一个新的转换数组。 map()方法没有这样的问题,它直接返回新的转换数组。建议在这种情况下使用 map() 方法。
2.链式调用其他方法
map() 方法的输出可以链式调用其他方法,例如 reduce()、sort()、filter(),从而可以在单个语句中执行多个操作。
另一方面,forEach()是一个终端方法意味着它不能链式调用其他方法,因为它返回undefined。 下面用这两种方法得到数组中每个元素的平方之和:
const numbers = [1, 2, 3, 4, 5];
// 使用 forEach()
const squareUsingForEach = []
let sumOfSquareUsingForEach = 0;
numbers.forEach(x => squareUsingForEach.push(x*x));
squareUsingForEach.forEach(square => sumOfSquareUsingForEach += square);
// 使用 map()
const sumOfSquareUsingMap = numbers.map(x => x*x).reduce((total, value) => total + value);
console.log(sumOfSquareUsingForEach); // 55
console.log(sumOfSquareUsingMap); // 55
当需要多个操作时,使用 forEach() 方法是一项无聊的工作。 在这种情况下,我们可以使用 map() 方法,更加的精炼。
3.性能
下面创建一个包含 100 万个随机数(范围从 1 到 1000)的数组。 让我们检验一下两种方法的性能如何。
// 数组:
var numbers = [];
for ( var i = 0; i < 1000000; i++ ) {
numbers.push(Math.floor((Math.random() * 1000) + 1));
}
// 1. forEach()
console.time("forEach");
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));
console.timeEnd("forEach");
// 2. map()
console.time("map");
const squareUsingMap = numbers.map(x => x*x);
console.timeEnd("map");
这是在 MacBook Pro 的 Google Chrome v83.0.4103.106(64 位)上运行上述代码后的结果。 建议复制上面的代码并在控制台中尝试一下。
forEach: 26.596923828125ms
map: 21.97998046875ms
显然 map() 方法在转换元素方面比 forEach() 执行得更好。
4.break迭代
在这点上,这两个方法没有区别,如果使用forEach()或map(),停止迭代唯一的方法是从回调函数中抛出异常。 如果我们在forEach()或 map()方法的回调函数中使用 break语句:
const numbers = [1, 2, 3, 4, 5];
// break; inside forEach()
const squareUsingForEach = [];
numbers.forEach(x => {
if(x == 3) break; // <- SyntaxError
squareUsingForEach.push(x*x);
});
// break; inside map()
const squareUsingMap = numbers.map(x => {
if(x == 3) break; // <- SyntaxError
return x*x;
});
JavaScript会抛出 SyntaxError:
ⓧ Uncaught SyntaxError: Illegal break statement
如果你需要终止循环,那么应该使用简单的 for 循环或 for-of / for-in 循环。
const numbers = [1, 2, 3, 4, 5];
// break; inside for-of loop
const squareUsingForEach = [];
for(x of numbers){
if(x == 3) break;
squareUsingForEach.push(x*x);
};
console.log(squareUsingForEach); // [1, 4]
5.总结
推荐使用 map() 来转换数组的元素,因为它语法短,可链式调用,性能更好。
如果不需要返回数组或不转换数组元素,则不应使用 map()。此时应该使用 forEach() 方法。
最后,如果想根据某些条件停止或中断数组的迭代,那么应该使用简单的 for 循环或 for-of / for-in 循环。
作者:Ashish Lahoti 译者:前端很美 来源:codingnconcepts