我当时就直接回他:“不能,我做不到。”
结果呢,这句话就像按了快进键,面试官突然宣布面试结束。
心里那个郁闷啊,我就问面试官:“这有啥不对吗?难道真的有办法在JavaScript中让forEach歇菜吗?”
还没等他回我,我就开始自我解惑,说出了我认为forEach不能停的理由。
我的小伙伴们,猜猜看,下面这段代码会打印出什么数字?
会只打印一个数字,还是一串数字?
正确答案是,它会打印出‘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循环是可以停的。
哦天啊,开什么国际玩笑呢。
要让他信服,我就得再来一次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++
}
}
确实,当我们用forEach遍历数组时,每个元素都要跑一遍回调函数,早退门都没有。
比如说,下面这段代码里,就算func1遇到了break,控制台还是会打印出‘2’。
const func1 = () => {
console.log(1)
return
}
const func2 = () => {
func1()
console.log(2)
}
func2()
你很棒,但我得告诉你,至少有三种方法可以让JavaScript里的forEach停止。
找到第一个大于或等于0的数字后,代码就进入死胡同了。所以控制台只会跟你说个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) {
}
哦!我的个神啊!我简直不敢相信,都快说不出话来。
别这么惊讶,面试官跟我说。
咱们还可以通过把数组长度设置成0来让forEach打卡下班。你也知道,数组没了,forEach自然也就不跑了。
const array = [ -3, -2, -1, 0, 1, 2, 3 ]
array.forEach((it) => {
if (it >= 0) {
console.log(it)
array.length = 0
}
})
哦!天哪,我的脑子都乱套了。
这招和第二招一个味儿,如果能把目标元素后面的值都给删了,forEach也就自动停工了。
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)
}
})
我瞪大了眼睛,真不想看这代码。太伤眼了。
最后我跟面试官说:“哎,可能你说的对,你确实找到了停forEach的方法,但要是用这种代码,我觉得你们老板迟早得让你走人。”
或许咱们应该考虑用for循环或者some方法来解决问题。
1. for
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
}
}
2. some
const array = [ -3, -2, -1, 0, 1, 2, 3 ]
array.some((it, i) => {
if (it >= 0) {
console.log(it)
return true
}
})
感谢您的阅读!如果您对本文有任何疑问或想要分享您的看法,请随时通过私信或在下方评论区与我交流。
页面更新:2024-03-01
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号