What is the best way to break out of a .each () jquery statement?

I have the following code:

$.each(data.People, function (i, person) {
   html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
        });

I want to change this code, so if the array (data.People) has more than 20 people, it will do what it does above for the first 20 people and then just show the text saying “X” to more people. so for example, if there were 100 people in the array, that would display the first 20, and then just say "another 80 people ..."

I suppose I need some kind of counter inside each expression, but he wanted to see the best way to get out of this and show the remaining text.

+5
source share
2 answers

return false each jQuery, break for JavaScript. return true continue.

X length , each , .

, :

$.each(data.People, function (i, person) {
   if (i == 20) {
     html.push("<p>" + (data.People.length - i) + " more people...</p>");
     return false;
   }
   html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
+13

i . , , return false, == 20 .

$.each(data.People, function (i, person) {
  if (i == 20) { return false; }
  html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
+7

All Articles