I recently came upon a jQuery construction I hadn't seen before. Here's a simplified version:
$([ '1', '2', '3' ]).each( function( index, value ) {
console.log( "index", index, "value", value );
});
This iterates over all the elements of the array [ '1', '2', '3' ]. The thing is, I'm used to seeing $(...) used with a CSS selector, but I haven't seen it used on a newly declared array, as is being done here. It seems to work, though (tested with Firefox 34 and Chromium 39).
Q1: Am I correct in understanding that this is equivalent to
var a = [ '1', '2', '3' ];
for ( var i = 0, value; value = a[i]; i++ ) {
console.log( "index", i, "value", value );
}
If not, what are the differences? (apart from the fact that this declares variables a, i and value).
Q2: As far as iterating over arrays in jQuery is concerned, I'm more used to $.each (not to be confused with $(selector).each as used above). Would the above be equivalent to
$.each( [ '1', '2', '3' ], function( index, value ){
console.log( "index", index, "value", value );
});
if yes, why are there two such extremely similar constructions in jQuery? Between the two, what is the preferred way to iterate over arrays, or is this just a matter of personal style?
$([ '1', '2', '3' ]).each. This will create a jQuery object that instead of containing DOM elements, will contain strings. You shouldn't do it that way, though. If you want to use jQuery, then you should do$.each( [ '1', '2', '3' ]. This is equivalent to doingvar a = [ '1', '2', '3' ]; a.forEach(function(v, i){});, as it's running a callback (closure) for each element.forEach$.fn.each()calls internally$.each()so there is no difference between both except the correct intend to use one or the other