I recently ran into a jQuery construct that I had not seen before. Here is a simplified version:
$([ '1', '2', '3' ]).each( function( index, value ) { console.log( "index", index, "value", value ); });
This iteration over all elements of the array [ '1', '2', '3' ] . The fact is that I'm used to seeing $(...) used with the CSS selector, but I have not seen it used in the newly declared array, as is done here. This seems to work (tested with Firefox 34 and Chromium 39).
Q1: Do I understand correctly that this is equivalent
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? (except that it declares the variables a , i and value ).
Q2: Regarding iteration over arrays in jQuery, I'm more used to $.each (not to be confused with $(selector).each , as used above). Higher would be equivalent
$.each( [ '1', '2', '3' ], function( index, value ){ console.log( "index", index, "value", value ); });
If so, why are there two such extremely similar constructs in jQuery? Between them, what is the preferred way to iterate over arrays, or is it just a matter of personal style?