JS數組中 forEach() 和 map() 的區別

譯者:前端小智
做者:Ashish Lahoti
來源:odingnconcepts
點贊再看,微信搜索 【大遷世界】關注這個沒有大廠背景,但有着一股向上積極心態人。本文 GitHub https://github.com/qq44924588... 上已經收錄,文章的已分類,也整理了不少個人文檔,和教程資料。**

雙12阿里服務器27塊,通用點擊這裏購買能夠找我返現30,等於27塊就能買到了,只限新用戶,能夠用家人的手機號購買!javascript

今天咱們來看一下 Array中 Array.forEach()Array.map()方法之間的區別。前端

forEach()map()方法一般用於遍歷Array元素,但幾乎沒有區別,咱們來一一介紹。java

1.返回值

forEach()方法返回undefined ,而map()返回一個包含已轉換元素的新數組。git

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()方法。github

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位)上運行上述代碼後的結果。 建議複製上面的代碼,而後在本身控制檯中嘗試一下。dom

forEach: 26.596923828125ms
map:     21.97998046875ms

顯然,map()方法比forEach()轉換元素要好。

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循環。


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:https://codingnconcepts.com/j...

交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索