JQuery $ .each (arr, foo) compared to $ (arr) .each (foo)

In jQuery, what's the difference between the following two constructs jQuery.each:

// Given
var arr = [1,2,3,4],
    results = [],
    foo = function (index, element) { 
       /* something done to/with each element */
       results.push(element * element); // arbitrary thing.
    }

// construction #1
$.each(arr, foo); // results = [1,4,9,16]

// construction #2
$(arr).each(foo); // results = [1,4,9,16]

Is there any difference, or is this purely syntax?

+5
source share
2 answers

$().each()is just a wrapper for $.each(), you can see it in the main code :

each: function( callback, args ) {
    return jQuery.each( this, callback, args );
}

Although $(something).each()intended for elements, I cannot promise that you will use it with a simple array that will not be interrupted later (it is unlikely that it will break because jQuery objects are wrapped arrays). The intended use directly causes $.each()in this case.

+8

, , .

jQuery - - .

jQuery :

function each(first,second)
{
    array = (instanceOf this == Array) ? this : ((first instanceOf Array) ? first : second);
    callback = (instanceOf second == Function) ? second : first;
    //As  you can see its testing what types are being sent to the fintion
}

first , this IE $([1,2,3,4]).each(callback), , first , second IE `$.each(array, callback );

. , .

, ,

+1

All Articles