原生js使用forEach()與jquery使用each()遍歷數組,return false 的區別:
1、使用each()遍歷數組a,如下:
var a=[20,21,22,23,24];
$.each(a, function(index,val) {
console.log('index='+index);
if(index==2){
return false;
}
console.log('val='+val);
});
結果如下:

從運行的效果可以看出,return 相當於循環中的break,直接結束整個循環。
2、使用forEach()遍歷數組a,如下:
var a=[20,21,22,23,24];
a.forEach(function(val,index){
console.log('index='+index);
if(index==2){
return false;
}
console.log('val='+val);
});
結果如下:

從運行的效果可以看出,return 相當於循環中的continue,跳出當前循環,後面的循環遍歷繼續。
本人也查過一些資料,我們可以通過自己寫判斷語句結束整個forEach()循環,或者使用for()循環遍歷。