在回答這個(gè)問(wèn)題時(shí),我的回答導(dǎo)致面試官突然結(jié)束了面試。
我對(duì)結(jié)果感到沮喪,問(wèn)面試官:“為什么?實(shí)際上可以停止 JavaScript 中的 forEach 循環(huán)嗎?”
在面試官回答之前,我花了一些時(shí)間解釋我對(duì)為什么我們不能直接停止 JavaScript 中的 forEach 循環(huán)的理解。
我的答案正確嗎?
小伙伴們,下面的代碼會(huì)輸出什么數(shù)字呢?
它會(huì)只輸出一個(gè)數(shù)字還是多個(gè)數(shù)字?
是的,它會(huì)輸出‘0’、‘1’、‘2’、‘3’。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]array.forEach((it) => { if (it >= 0) { console.log(it) return // or break }})
這是正確的!我向面試官展示了這段代碼,但他仍然相信我們可以停止 JavaScript 中的 forEach 循環(huán)。
天哪,你一定是在開玩笑。
為什么?
為了說(shuō)服他,我不得不再次實(shí)現(xiàn)forEach模擬。
Array.prototype.forEach2 = function (callback, thisCtx) { if (typeof callback !== 'function') { throw `${callback} is not a function` } const length = this.length let i = 0 while (i < length) { if (this.hasOwnProperty(i)) { // Note here:Each callback function will be executed once callback.call(thisCtx, this[ i ], i, this) } i++ }}
是的,當(dāng)我們使用“forEach”迭代數(shù)組時(shí),回調(diào)將為數(shù)組的每個(gè)元素執(zhí)行一次,并且我們無(wú)法過(guò)早地?cái)[脫它。
例如,在下面的代碼中,即使“func1”遇到break語(yǔ)句,“2”仍然會(huì)輸出到控制臺(tái)。
const func1 = () => { console.log(1) return}const func2 = () => { func1() console.log(2)}func2()
你太棒了,但我想告訴你,我們至少有 3 種方法可以在 JavaScript 中停止 forEach。
當(dāng)我們找到第一個(gè)大于或等于0的數(shù)字后,這段代碼將無(wú)法繼續(xù)。所以控制臺(tái)只會(huì)打印出0。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]try { array.forEach((it) => { if (it >= 0) { console.log(it) throw Error(`We've found the target element.`) } })} catch (err) {}
哦!我的天啊!我簡(jiǎn)直不敢相信,這讓我無(wú)法說(shuō)話。
請(qǐng)不要那么驚訝,面試官對(duì)我說(shuō)。
我們還可以通過(guò)將數(shù)組的長(zhǎng)度設(shè)置為0來(lái)中斷forEach。如您所知,如果數(shù)組的長(zhǎng)度為0,forEach將不會(huì)執(zhí)行任何回調(diào)。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]array.forEach((it) => { if (it >= 0) { console.log(it) array.length = 0 }})
我的心已經(jīng)亂了。
思路和方法2一樣,如果能刪除目標(biāo)元素后面的所有值,那么forEach就會(huì)自動(dòng)停止。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]array.forEach((it, i) => { if (it >= 0) { console.log(it) // Notice the sinful line of code array.splice(i + 1, array.length - i) }})
我睜大了眼睛,我不想讀這段代碼。這不好。
請(qǐng)用for或some
我對(duì)面試官說(shuō):“哦,也許你是對(duì)的,你設(shè)法在 JavaScript 中停止了 forEach,但我認(rèn)為你的老板會(huì)解雇你,因?yàn)檫@是一個(gè)非常糟糕的代碼片段。
我不喜歡做那樣的事;這會(huì)讓我的同事討厭我。”
也許我們應(yīng)該使用“for”或“some”方法來(lái)解決這個(gè)問(wèn)題。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]for (let i = 0, len = array.length; i < len; i++) { if (array[ i ] >= 0) { console.log(array[ i ]) break }}
const array = [ -3, -2, -1, 0, 1, 2, 3 ]array.some((it, i) => { if (it >= 0) { console.log(it) return true }})
雖然面試官以這個(gè)問(wèn)題結(jié)束了面試,但我很慶幸自己沒(méi)有加入公司,不想為了某種目的而寫出一段臭代碼。 這樣的面試官也不是面試者所喜歡的,為了面試而面試的面試官和面試題,讓面試者覺(jué)得有點(diǎn)無(wú)辜與無(wú)奈。
不管怎么樣,還是努力提升自己的技能吧。
最后,感謝您的閱讀。
本文鏈接:http://www.www897cc.com/showinfo-26-5742-0.html面試官:你能停止 JavaScript 中的 forEach 循環(huán)嗎?
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com