沐鳴下載_JS數組中 forEach() 和 map() 的區別

當需要多個操作時,使用forEach()方法是一項非常乏味的工作。我們可以在這種情況下使用map()方法。,
,由於forEach()返回undefined,所以我們需要傳遞一個空數組來創建一個新的轉換后的數組。map()方法不存在這樣的問題,它直接返回新的轉換后的數組。在這種情況下,建議使用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],// 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位)上運行上述代碼后的結果。 建議複製上面的代碼,然後在自己控制台中嘗試一下。,
,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,map()方法輸出可以與其他方法(如reduce()、sort()、filter())鏈接在一起,以便在一條語句中執行多個操作。,另一方面,forEach()是一個終端方法,這意味着它不能與其他方法鏈接,因為它返回undefined。,我們使用以下兩種方法找出數組中每個元素的平方和:,當需要多個操作時,使用forEach()方法是一項非常乏味的工作。我們可以在這種情況下使用map()方法。