Using $ (array) .each to iterate over an array

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?

+5
source share
2 answers

Q1. Yes.

Q2. jQuery takes arrays (and objects of type array) and turns them into jQuery objects.

You can easily see this by issuing in the browser console:

 console.dir($([ '1', '2', '3' ])) > VM199:2 e.fn.e.init[3] 

Returns the jQuery object that invokes the call. They can be repeated using .each() . This tool is for you to do this (a far-fetched example):

 $(document.getElementsByTagName("A")).each(func); 

Doing this with a simple array of strings works and is likely to continue working in the future, however, I still see this as a misuse of the API and recommend the correct approach:

 $.each(['1', '2', '3' ], func); 
+4
source

Q1 : As another said, yes.

Q2 : Start by not saying because you can do it.

It is true that you can use $([ '1', '2', '3' ]).each() and it will work, but it is inefficient.

Both do not match (they are similar though). As the jQuery doc says:

Function $.each() does not coincide with the $(selector).each() , which is used to iterate over the object only jQuery. The $.each() function can be used to iterate over any collection, be it an object or an array.

This means that if you use $([ '1', '2', '3' ]).each() , you create a jQuery object that is not needed. This is much faster, in terms of performance, by each property of a jQuery object and then calling the function that passes the array than calling the function that creates the jQuery array and then accessing its prototype .each() .

+3
source

Source: https://habr.com/ru/post/1210411/


All Articles