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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With