原生js使用forEach()與jquery使用each遍歷數組,return false 的區別

原生js使用forEach()與jquery使用each()遍歷數組,return false 的區別: jquery

一、使用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);
    });

結果以下: spa

從運行的效果能夠看出,return 至關於循環中的break,直接結束整個循環。 code

二、使用forEach()遍歷數組a,以下:blog

    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);
  });

結果以下: io

從運行的效果能夠看出,return 至關於循環中的continue,跳出當前循環,後面的循環遍歷繼續。 
本人也查過一些資料,咱們能夠經過本身寫判斷語句結束整個forEach()循環,或者使用for()循環遍歷。console

相關文章
相關標籤/搜索