MedicineMan
MedicineMan

Reputation: 15324

in jquery, what does $.each mean?

what does the following mean?

$.each(json.results, function(i, item) {
    ...
}

I kind of understand the other parts of the line, but if you could explain that as well, I'd appreciate it.

Upvotes: 1

Views: 2244

Answers (4)

Doug Neiner
Doug Neiner

Reputation: 66201

$.each provides a simple iterator and it will execute the callback function once for each element in the array.

For my examples, lets assume:

var json = {
   results: [1, 2, 3]
};

In addition to using the parameters (index, item), the this variable in each callback can be used to reference the current item.

UPDATE: This example changed to show use of the other parameters:

$.each( json.results, function(index, item){
   console.log(this + " " + index + " " + item);
});
// Outputs:
// 1 0 1
// 2 1 2
// 3 2 3

The first parameter is the index of the current item in the loop. It is a zero based index. The second parameter is the item of the current iteration. You can use this or the variable, but the variable comes in handy in situations like this:

$.each (json.results, function(index, item){
   // this == number
   // item == number
   $('div').click(function(e){
      // this == div
      // item == number
   });
});

Additionally, there are a few controls you can use similar to the break and continue statements.

If you want to continue or next at any point, use return true;

$.each( json.results, function(i, item){
  if(this == 2) return true;
  // do something else
});

If you want to break, use return false;

var f;
$.each( json.results, function(i, item){
   if(this == 2){
      f = this;
      return false; // exits the iterator
   }
});

Upvotes: 3

Sampson
Sampson

Reputation: 268414

It just means you want to do something with each result found in json.results. Within the curly-braces, the current result you're handling is known by this, so you could do something like:

var json = { 'results':{'name':'jonathan', 'age':'26'} };

$.each(json.results, function(i,o){
  alert(this);
  // First iteration : 'Jonathan'
  // Second Iteration: '26'
});

Upvotes: 1

nickf
nickf

Reputation: 546243

It iterates over the members of an object. An example:

var obj = {
    alpha : 'A',
    beta : 'B',
    3 : 'C'
};

$.each(obj, function(key, val) {
    console.log(key);    // alpha, beta, 3
    console.log(val);    // A, B, C
    console.log(this);   // A, B, C
});

Edit: Actually the above is a bad example of the context of this, because if your value is a string or number, it's converted from the literal ("C") to an object (new String("C")), but for other things (functions, elements, arrays, etc) it's untouched.

Upvotes: 0

Alex Gaynor
Alex Gaynor

Reputation: 15019

$.each is basically an iteration idiom, similar to javascripts:

for (x in container)

except it iterates over values, instead of keys (or indices in the array case).

Upvotes: 0

Related Questions