Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While looping through results with $.each, how do you refer to the index of the current iteration?

If I'm looping through results from a JSON call, how do I know if I'm on the first iteration?

In this example I made up the loopIndex variable to indicate what I'm looking for -- but it's not actually set anywhere.

How do you know where you are in the loop - which iteration you're on?

$.getJSON(myurl, function(data) {
  $.each(data.results, function() {
     // what's the index of this iteration?
     if(loopIndex==0){
      console.log("first iteration!");
     }

  });
});
like image 397
Paul Avatar asked Dec 01 '25 17:12

Paul


2 Answers

The first parameter to the $.each() callback is the index, like this:

$.getJSON("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=paparazzi+lady+gaga&callback=?", function(data) {
  $.each(data.results, function(i, item) {
     if(i==o) {
       console.log("first iteration!");
     }
  });
});

The signature for .Query.each() is:

jQuery.each(collection, callback(indexInArray, valueOfElement))
like image 77
Nick Craver Avatar answered Dec 03 '25 08:12

Nick Craver


  $.each(data.results, function(loopIndex) {
     .....

as shown in the documentation of jQuery.each.

like image 21
kennytm Avatar answered Dec 03 '25 07:12

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!