js中 Array.forEach如何跳出回圈
forEach是不能通過break或者return跳出回圈的,一般跳出回圈的方式為拋出例外:
try {
let array = [1, 2, 3, 4]
array.forEach((item, index) => {
if (item === 3) {
throw new Error('end')//報錯,就跳出回圈
} else {
console.log(item)
}
})
} catch (e) {
}
這種寫法反而很麻煩,
解決方式:
1.使用every替代:
let array = [1, 2, 3, 4]
array.every((item, index) => {
if (item === 3) {
return true
} else {
console.log(item)
}
})
2.自己寫一個😁
//可跳出回圈的陣列遍歷
Array.prototype.loop = function(cbk) {
//判斷當前陣列是否為空
if (this?.length) {
for (let i = 0; i < this.length; i++) {
let stop = cbk(this[i], i, this)
//判斷是否停止回圈
if (stop) {
break
}
}
}
}
let array = [1, 2, 3, 4]
array.loop ((item, index) => {
if (item === 3) {
return true
} else {
console.log(item)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/296605.html
標籤:其他
上一篇:記錄日常使用的Helper檔案
