Malte Skoruppa
Malte Skoruppa

Reputation: 1242

Using $(array).each to iterate over array

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?

Upvotes: 5

Views: 4409

Answers (2)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

Q1: As other said, yes.

Q2: Ill start by saying not because you can that you should.

It is right that you can use $([ '1', '2', '3' ]).each() and it will work, but it isn't efficient.

Both are not the same (they are similar though). As said in the jQuery doc:

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Which mean that if you use $([ '1', '2', '3' ]).each() you are creating a jQuery object which is not needed. It is way faster, performance wise, the property each of the jQuery object then calling the function passing an array than calling a function creating a jQuery object of an array and then access to its prototype .each().

Upvotes: 3

Tomalak
Tomalak

Reputation: 338406

Q1. Yes.

Q2. jQuery accepts arrays (and array-like objects) and turns them into jQuery objects.

You can see that easily by issuing, on the browser console:

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

That's a jQuery object that call returns. They can be iterated over with .each(). This facility is meant to enable you to do this (contrived example):

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

Doing so with a plain array of strings works, and will likely continue to work in the future, however I still see that as a mis-use of the API and would recommend the proper approach:

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

Upvotes: 4

Related Questions