Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

sakatagintoki
12,624 PointsHow to break out of a jQuery $.each() loop at a certain index value?
So, I know how to stop an each loop from iterating over objects in an array immediately.
$.each(objects, function(object) {
return false;
}
But I want to stop the each loop iterating over the objects in the array at a certain index position. Say, when the $.each loop hits the third object, it exits.
I've tried
\\ If the each loop hits the 4th object in the array named objects...
if(object[3]) {
return false;
}
But this hasn't worked.
Thanks ~Jay
2 Answers

Marcus Parsons
15,719 PointsHi Jay,
With the jQuery $.each function, you don't have to specify a counter variable outside of the loop because your variable object
is actually an optional index variable. So that it makes more sense let's rename that to index
and I'll show you what I mean. You can also put a second optional parameter that is a value so I'm going to name it val
. All you need to do is test that the index is greater than 3, and that's it!
$.each(objects, function(index, val) {
if (index > 3) {
return false;
}
//I only put this to show what these variables do for you
console.log("At index " + index + ", there is a value of " + val);
}

Christopher van Ruitenbeek
13,705 PointsTry:
\\ If the each loop hits the 4th object in the array named objects...
if (object[3]) {
break;
}

sakatagintoki
12,624 PointsI just solved it
var i = 0 \\ Set a counter variable outside the loop
$.each(objects, function(object) {
if(++i > 3) {
return false;
}
}
But thanks for responding (:
sakatagintoki
12,624 Pointssakatagintoki
12,624 PointsYes your syntax is better. I was following an example I fond elsewhere exactly, even though I felt it was a little awkward it worked.
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsIt's just each method functions differently. If you need access to the index of a certain object after the each loop has ran, the method you found would give you that since the index is created outside of the loop. But if you don't need access to that index, you can use the optional parameters for
jQuery.each
. Just adapt the code to what suits what you need best! =]