面試官:有了 for 循環(huán),為什么還要 forEach ??
作者:技術(shù)直男星辰
來(lái)源:juejin.cn/post/7018097650687803422
for循環(huán)和forEach的本質(zhì)區(qū)別。
for循環(huán)和forEach的語(yǔ)法區(qū)別。
for循環(huán)和forEach的性能區(qū)別。
本質(zhì)區(qū)別

看代碼
let arr = [1, 2, 3, 4] // 可迭代對(duì)象let iterator = arr[Symbol.iterator]() // 調(diào)用 Symbol.iterator 后生成了迭代器對(duì)象console.log(iterator.next()); // {value: 1, done: false} 訪問(wèn)迭代器對(duì)象的next方法console.log(iterator.next()); // {value: 2, done: false}console.log(iterator.next()); // {value: 3, done: false}console.log(iterator.next()); // {value: 4, done: false}console.log(iterator.next()); // {value: undefined, done: true}
let arr = [1, 2, 3, 4]for (const item of arr) {console.log(item); // 1 2 3 4}
function num(params) {console.log(arguments); // Arguments(6) [1, 2, 3, 4, callee: ?, Symbol(Symbol.iterator): ?]let iterator = arguments[Symbol.iterator]()console.log(iterator.next()); // {value: 1, done: false}console.log(iterator.next()); // {value: 2, done: false}console.log(iterator.next()); // {value: 3, done: false}console.log(iterator.next()); // {value: 4, done: false}console.log(iterator.next()); // {value: undefined, done: true}}num(1, 2, 3, 4)let set = new Set('1234')set.forEach(item => {console.log(item); // 1 2 3 4})let iterator = set[Symbol.iterator]()console.log(iterator.next()); // {value: 1, done: false}console.log(iterator.next()); // {value: 2, done: false}console.log(iterator.next()); // {value: 3, done: false}console.log(iterator.next()); // {value: 4, done: false}console.log(iterator.next()); // {value: undefined, done: true}
感興趣的同學(xué)可以搜下 forEach 源碼, Array Set Map 實(shí)例上都掛載著 forEach ,但網(wǎng)上的答案大多數(shù)是通過(guò) length 判斷長(zhǎng)度, 利用for循環(huán)機(jī)制實(shí)現(xiàn)的。但在 Set Map 上使用會(huì)報(bào)錯(cuò),所以我認(rèn)為是調(diào)用的迭代器,不斷調(diào)用 next,傳參到回調(diào)函數(shù)。由于網(wǎng)上沒(méi)查到答案也不妄下斷言了,有答案的人可以評(píng)論區(qū)給我留言
了解了本質(zhì)區(qū)別,在應(yīng)用過(guò)程中,他們到底有什么語(yǔ)法區(qū)別呢?
forEach 的參數(shù)。
forEach 的中斷。
forEach 刪除自身元素,index不可被重置。
for 循環(huán)可以控制循環(huán)起點(diǎn)。
1.forEach 的參數(shù)
我們真正了解 forEach 的完整傳參內(nèi)容嗎?它大概是這樣:
arr.forEach((self,index,arr) =>{},this)self:數(shù)組當(dāng)前遍歷的元素,默認(rèn)從左往右依次獲取數(shù)組元素。
index: 數(shù)組當(dāng)前元素的索引,第一個(gè)元素索引為0,依次類推。
arr:當(dāng)前遍歷的數(shù)組。
this: 回調(diào)函數(shù)中this指向。
let arr = [1, 2, 3, 4];let person = {name: '技術(shù)直男星辰'};arr.forEach(function (self, index, arr) {console.log(`當(dāng)前元素為${self}索引為${index},屬于數(shù)組${arr}`);console.log(this.name+='真帥');}, person)
我們可以利用 arr 實(shí)現(xiàn)數(shù)組去重:
let arr1 = [1, 2, 1, 3, 1];let arr2 = [];arr1.forEach(function (self, index, arr) {arr1.indexOf(self) === index ? arr2.push(self) : null;});console.log(arr2); // [1,2,3]

2.forEach 的中斷
let arr = [1, 2, 3, 4],i = 0,length = arr.length;for (; i < length; i++) {console.log(arr[i]); //1,2if (arr[i] === 2) {break;};};arr.forEach((self,index) => {console.log(self);if (self === 2) {break; //報(bào)錯(cuò)};});arr.forEach((self,index) => {console.log(self);if (self === 2) {continue; //報(bào)錯(cuò)};});
如果我一定要在 forEach 中跳出循環(huán)呢?其實(shí)是有辦法的,借助try/catch:
try {var arr = [1, 2, 3, 4];arr.forEach(function (item, index) {//跳出條件if (item === 3) {throw new Error("LoopTerminates");}//do somethingconsole.log(item);});} catch (e) {if (e.message !== "LoopTerminates") throw e;};
若遇到 return 并不會(huì)報(bào)錯(cuò),但是不會(huì)生效
let arr = [1, 2, 3, 4];function find(array, num) {array.forEach((self, index) => {if (self === num) {return index;};});};let index = find(arr, 2);// undefined
3.forEach 刪除自身元素,index不可被重置
let arr = [1,2,3,4]arr.forEach((item, index) => {console.log(item); // 1 2 3 4index++;});
4.for 循環(huán)可以控制循環(huán)起點(diǎn)
let arr = [1, 2, 3, 4],i = 1,length = arr.length;for (; i < length; i++) {console.log(arr[i]) // 2 3 4};
那之前的數(shù)組遍歷并刪除滋生的操作就可以寫成
let arr = [1, 2, 1],i = 0,length = arr.length;for (; i < length; i++) {// 刪除數(shù)組中所有的1if (arr[i] === 1) {arr.splice(i, 1);//重置i,否則i會(huì)跳一位i--;};};console.log(arr); // [2]//等價(jià)于var arr1 = arr.filter(index => index !== 1);console.log(arr1) // [2]
在性能對(duì)比方面我們加入一個(gè) map 迭代器,它與 filter 一樣都是生成新數(shù)組。我們對(duì)比 for forEach map 的性能在瀏覽器環(huán)境中都是什么樣的:
在chrome 62 和 Node.js v9.1.0環(huán)境下:for 循環(huán)比 forEach 快1倍,forEach 比 map 快20%左右。另外,搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師后臺(tái)回復(fù)“2T”,獲取一份驚喜禮包。
原因分析
for:for循環(huán)沒(méi)有額外的函數(shù)調(diào)用棧和上下文,所以它的實(shí)現(xiàn)最為簡(jiǎn)單。
forEach:對(duì)于forEach來(lái)說(shuō),它的函數(shù)簽名中包含了參數(shù)和上下文,所以性能會(huì)低于 for 循環(huán)。
map:map 最慢的原因是因?yàn)?map 會(huì)返回一個(gè)新的數(shù)組,數(shù)組的創(chuàng)建和賦值會(huì)導(dǎo)致分配內(nèi)存空間,因此會(huì)帶來(lái)較大的性能開(kāi)銷。如果將map嵌套在一個(gè)循環(huán)中,便會(huì)帶來(lái)更多不必要的內(nèi)存消耗。
當(dāng)大家使用迭代器遍歷一個(gè)數(shù)組時(shí),如果不需要返回一個(gè)新數(shù)組卻使用 map 是違背設(shè)計(jì)初衷的。在我前端合作開(kāi)發(fā)時(shí)見(jiàn)過(guò)很多人只是為了遍歷數(shù)組而用 map 的:
let data = [];let data2 = [1,2,3];data2.map(item=>data.push(item));
正文結(jié)束
2.深圳一普通中學(xué)老師工資單曝光,秒殺程序員,網(wǎng)友:敢問(wèn)是哪個(gè)學(xué)校畢業(yè)的?
3.從零開(kāi)始搭建創(chuàng)業(yè)公司后臺(tái)技術(shù)棧
4.程序員一般可以從什么平臺(tái)接私活?
5.清華大學(xué):2021 元宇宙研究報(bào)告!
6.為什么國(guó)內(nèi) 996 干不過(guò)國(guó)外的 955呢?
7.這封“領(lǐng)導(dǎo)痛批95后下屬”的郵件,句句扎心!
8.15張圖看懂瞎忙和高效的區(qū)別!

