JS陣列中 forEach() 和 map() 的區別
阿新 • • 發佈:2021-08-16
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。
我們使用以下兩種方法找出陣列中每個元素的平方和:
onst 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.效能
// Array:
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()轉換元素要好。
https://www.houdianzi.com/ logo設計公司
4.中斷遍歷
這兩種方法都不能用 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;
});
上面程式碼會丟擲 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()轉換陣列的元素,因為它語法短,可連結且效能更好。
如果不想返回的陣列或不轉換陣列的元素,則使用forEach() 方法。
最後,如果要基於某種條件停止或中斷陣列的便利,則應使用簡單的for迴圈或for-of / for-in迴圈。