forEach循環不能被終止
舉個栗子//該栗子主要是爲了實現數組的indexof()
function indexOf(arr,item){
arr.forEach((v,i)=>{
if(arr === 2){
return i
}
console.log(i)
})
return -1
}
indexOf([1,2,3],2)
forEach()無法在所有元素都傳遞給調用的函數之前終止遍歷 -----摘抄《JavaScript權威指南》(第6版) 7.9.1
解決方案
1.使用for循環
2.必須把forEach()方法放在一個try塊中,並能拋出一個異常錯誤