JavaScript中的map()和forEach()有什么區(qū)別?

2020-7-4    seo達(dá)人

閱讀之前

基本上,在JavaScript中遍歷對(duì)象取決于對(duì)象是否可迭代。默認(rèn)情況下,數(shù)組是可迭代的。map 和 forEach 包含在Array.prototype 中,因此我們無(wú)需考慮可迭代性。如果你想進(jìn)一步學(xué)習(xí),我推薦你看看什么是JavaScript中的可迭代對(duì)象!


什么是map()和forEach()?

map 和 forEach 是數(shù)組中的幫助器方法,可以輕松地在數(shù)組上循環(huán)。我們?cè)?jīng)像下面這樣循環(huán)遍歷一個(gè)數(shù)組,沒(méi)有任何輔助函數(shù)。


var array = ['1', '2', '3'];

for (var i = 0; i < array.length; i += 1) {

 console.log(Number(array[i]));

}

// 1

// 2

// 3

自JavaScript時(shí)代開始以來(lái),就一直存在 for 循環(huán)。它包含3個(gè)表達(dá)式:初始值,條件和最終表達(dá)式。


這是循環(huán)數(shù)組的經(jīng)典方法。從ECMAScript 5開始,新功能似乎使我們更加快樂(lè)。


map

map 的作用與 for 循環(huán)完全相同,只是 map 會(huì)創(chuàng)建一個(gè)新數(shù)組,其結(jié)果是在調(diào)用數(shù)組中的每個(gè)元素上調(diào)用提供的函數(shù)。


它需要兩個(gè)參數(shù):一個(gè)是稍后在調(diào)用 map 或 forEach 時(shí)調(diào)用的回調(diào)函數(shù),另一個(gè)是回調(diào)函數(shù)被調(diào)用時(shí)使用的名為 thisArg 的上下文變量。


const arr = ['1', '2', '3'];

// 回調(diào)函數(shù)接受3個(gè)參數(shù)

// 數(shù)組的當(dāng)前值作為第一個(gè)參數(shù)

// 當(dāng)前值在數(shù)組中的位置作為第二個(gè)參數(shù)

// 原始源數(shù)組作為第三個(gè)參數(shù)

const cb = (str, i, origin) => {

 console.log(`${i}: ${Number(str)} / ${origin}`);

};

arr.map(cb);

// 0: 1 / 1,2,3

// 1: 2 / 1,2,3

// 2: 3 / 1,2,3

回調(diào)函數(shù)可以如下使用。


arr.map((str) => { console.log(Number(str)); })

map 的結(jié)果不等于原始數(shù)組。


const arr = [1];

const new_arr = arr.map(d => d);


arr === new_arr; // false

你還可以將對(duì)象作為 thisArg 傳遞到map。


const obj = { name: 'Jane' };


[1].map(function() {

 // { name: 'Jane' }

 console.dir(this);

}, obj);


[1].map(() => {

 // window

 console.dir(this);

}, obj);

對(duì)象 obj 成為 map 的 thisArg。但是箭頭回調(diào)函數(shù)無(wú)法將 obj 作為其 thisArg。


這是因?yàn)榧^函數(shù)與正常函數(shù)不同。


forEach

forEach 是數(shù)組的另一個(gè)循環(huán)函數(shù),但 map 和 forEach 在使用中有所不同。map 和 forEach 可以使用兩個(gè)參數(shù)——回調(diào)函數(shù)和 thisArg,它們用作其 this。


const arr = ['1', '2', '3'];

// 回調(diào)函數(shù)接受3個(gè)參數(shù)

// 數(shù)組的當(dāng)前值作為第一個(gè)參數(shù)

// 當(dāng)前值在數(shù)組中的位置作為第二個(gè)參數(shù)

// 原始源數(shù)組作為第三個(gè)參數(shù)

const cb = (str, i, origin) => {

 console.log(`${i}: ${Number(str)} / ${origin}`);

};

arr.forEach(cb);

// 0: 1 / 1,2,3

// 1: 2 / 1,2,3

// 2: 3 / 1,2,3

那有什么不同?


map 返回其原始數(shù)組的新數(shù)組,但是 forEach 卻沒(méi)有。但是它們都確保了原始對(duì)象的不變性。


[1,2,3].map(d => d + 1); // [2, 3, 4];

[1,2,3].forEach(d => d + 1); // undefined;

如果更改數(shù)組內(nèi)的值,forEach 不能確保數(shù)組的不變性。這個(gè)方法只有在你不接觸里面的任何值時(shí),才能保證不變性。


[{a: 1, b: 2}, {a: 10, b: 20}].forEach((obj) => obj.a += 1);

// [{a: 2, b: 2}, {a: 11, b: 21}]

// 數(shù)組已更改!

何時(shí)使用map()和forEach()?

由于它們之間的主要區(qū)別在于是否有返回值,所以你會(huì)希望使用 map 來(lái)制作一個(gè)新的數(shù)組,而使用 forEach 只是為了映射到數(shù)組上。


這是一個(gè)簡(jiǎn)單的例子。


const people = [

 { name: 'Josh', whatCanDo: 'painting' },

 { name: 'Lay', whatCanDo: 'security' },

 { name: 'Ralph', whatCanDo: 'cleaning' }

];


function makeWorkers(people) {

 return people.map((person) => {

   const { name, whatCanDo } = person;

   return <li key={name}>My name is {name}, I can do {whatCanDo}</li>

 });

}


<ul>makeWorkers(people)</ul>

比如在React中,map 是非常常用的制作元素的方法,因?yàn)?map 在對(duì)原數(shù)組的數(shù)據(jù)進(jìn)行操作后,會(huì)創(chuàng)建并返回一個(gè)新的數(shù)組。


const mySubjectId = ['154', '773', '245'];


function countSubjects(subjects) {

 let cnt = 0;

 

 subjects.forEach(subject => {

   if (mySubjectId.includes(subject.id)) {

     cnt += 1;

   }

 });

 

 return cnt;

}


countSubjects([

 { id: '223', teacher: 'Mark' },

 { id: '154', teacher: 'Linda' }

]);

// 1

另一方面,當(dāng)你想對(duì)數(shù)據(jù)進(jìn)行某些操作而不創(chuàng)建新數(shù)組時(shí),forEach 很有用。順便說(shuō)一句,可以使用 filter 重構(gòu)示例。


subjects.filter(subject => mySubjectId.includes(subject.id)).length;

綜上所述,我建議你在創(chuàng)建一個(gè)新的數(shù)組時(shí)使用map,當(dāng)你不需要制作一個(gè)新的數(shù)組,而是要對(duì)數(shù)據(jù)做一些事情時(shí),就使用forEach。


速度比較

有些帖子提到 map 比 forEach 快。所以,我很好奇這是不是真的。我找到了這個(gè)對(duì)比結(jié)果。






該代碼看起來(lái)非常相似,但結(jié)果卻相反。有些測(cè)試說(shuō) forEach 更快,有些說(shuō) map 更快。也許你在告訴自己 map/forEach 比其他的快,你可能是對(duì)的。老實(shí)說(shuō),我不確定。我認(rèn)為在現(xiàn)代Web開發(fā)中,可讀性比 map 和 forEach 之間的速度重要得多。


但可以肯定的是——兩者都比JavaScript內(nèi)置的 for 循環(huán)慢。

藍(lán)藍(lán)設(shè)計(jì)www.bouu.cn )是一家專注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)




分享本文至:

日歷

鏈接

個(gè)人資料

存檔