foreach沒法return - 如何中斷foreach循環

前言


數組的 forEach 用於循環遍歷數據,會對數組中有效的每一項執行一次回調函數,可是在遍歷回調中使用 break 或 continue 會報錯,使用 return 也沒法終止循環。數組

語法


Array.forEach((currentValue, index, array, thisArg) => {})bash

  • currentValue: 數組中正在處理的當前元素。
  • index(可選): 數組中正在處理的當前元素的索引。
  • array(可選): forEach() 方法正在操做的數組。
  • thisArg(可選): 當執行回調函數時用做 this 的值(參考對象)。

使用 break


let arr = [1, 2, 3]
arr.forEach(item => {
	if (item === 2) {
		break // 報錯
	}
	console.log(item)
})
複製代碼

使用 continue


let arr = [1, 2, 3]
arr.forEach(item => {
	if (item === 2) {
		continue // 報錯
	}
	console.log(item)
})
複製代碼

使用 return


let arr = [1, 2, 3]
arr.forEach(item => {
    if (item === 2) {
    	return
    }
    console.log(item)
})
複製代碼

從圖中能夠看出 return 並無終止 forEach 循環,仍是繼續循環打印出了 3 。

使用try...catch來終止循環

let arr = [1, 2, 3]
try {
	arr.forEach(item => {
		if (item === 2) {
			throw('循環終止')
		}
		console.log(item)
	})
} catch(e) {
	console.log('e: ', e)
}
複製代碼

從圖中能夠看到,當循環到第二項時拋出了錯誤,從而使得forEach沒有再進行下去

使用其餘語法代替

// 使用 Array.some()
arr.some(item => {
	console.log('b: ',item) 
	return item === 2 // 當有數組有一項知足條件時結束並返回true
})

// 使用 Array.ervey()
arr.every(item => {
	console.log('c: ',item)
	return item !== 2 // 檢查數字中是否每一項都知足條件,若是有一項不知足就結束循環並返回false
})
複製代碼
相關文章
相關標籤/搜索