jQuery.each implementation differs from native Array.forEach

前端 未结 3 1982
星月不相逢
星月不相逢 2020-12-09 09:11

Does anyone why is the otherwise excellent jQuery.each function is designed differently from the (now) native Array.forEach? F.ex:

         


        
3条回答
  •  庸人自扰
    2020-12-09 09:51

    Well, I guess we'd have to ask Mr. Resig himself for an explanation on this. Fact is, that ECMAscript 262 edition 5 wasn't very widespread the time jQuery was designed and developed, so this definitely comes into play. And since it was designed like so, they didn't want to change it later and break all existing code.

    In fact, its much more likely that you want to access an element with a higher priority, than the index of it when looping an Array. So, to me there is no reasonable explanation why you would pass in the index first into the callbacks.

    Be assured, if jQuery was invented today, they would follow the native implementation behavior.

    On the other hand, if it bugs you too much you can simply create a shortcut and use the native Array.prototype.forEach to iterate your jQuery wrapped sets:

    var forEach = Function.prototype.call.bind( Array.prototype.forEach );
    
    forEach( $('div'), function( node ) {
        console.log( node );
    });
    

    ..and for standard Arrays, just go with their native prototype.

    while implementation conditional return false/true,we must know what part work in which manner. When you use return false with condition in Array.prototype.forEach it treated as continue, but When you use return false, with condition in $.each it treated as break statement.

    var listArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    var arr1 =[];var arr2=[];
    var rv = true;
    listArray.forEach(function(i, item) {
      if (i == 5) {
        return rv = false;
      }
     arr1.push(i)
      return rv;
    });
    var listArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    jQuery.each(listArray, function(i, item) {
      if (item == 5) {
        return rv = false;
      }
      arr2.push(i)
    });
      console.log("forEach=>"+arr1)
      console.log("$.each=>"+arr2)

提交回复
热议问题