Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.each(arr, foo) versus $(arr).each(foo)

In jQuery, what's the difference between the following two constructions of 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 it purely syntax?

like image 851
Brian M. Hunt Avatar asked Jun 08 '10 12:06

Brian M. Hunt


1 Answers

The $().each() is just a wrapper for $.each(), you can see this in the core code:

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

Though, $(something).each() is intended for elements, I can't promise you using it with a plain array won't break later (it's unlikely it'll break, since jQuery objects are wrapped arrays though). The intended use is directly calling $.each() in this case.

like image 198
Nick Craver Avatar answered Oct 17 '22 22:10

Nick Craver