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!");
}
});
});
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))
$.each(data.results, function(loopIndex) {
.....
as shown in the documentation of jQuery.each.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With