Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple for loop

I have this simple for loop but unfortunately I'm unable to run it successfully.

This is what I have:

For Loop

 var imagesPerPage = 2

  for (i = 0; i < response.d.length; i++) {
    if (i > imagesPerPage) {
     alert('more');
     }else{
     alert('less');
     }
  }

When I run this code first If I have <= 2 then I get "less" alert twice. But when I have > 2 then I get "less" alert twice and "more" alert once.

Can anyone say me where am I going wrong?

like image 629
coder Avatar asked Jan 19 '26 21:01

coder


2 Answers

Why not use a simple if construct for this?

var imagesPerPage = 2

if ( response.d.length > imagesPerPage ) {
  alert('more');
} else {
  alert('less');
}

In your code the loop runs always response.d.length times. In the first two times the false part of your if fires and results in the two "more" alerted. After that all other runs use the true part of your if-clause and will return "more". In any case all runs are done no matter what you alert.

You can however stop the loop by inserting a break command at the point you want to leave the loop. This, however, oftentimes leads to very unclear code and thus should be avoided if possible. (Besides, I doubt, that this would be your desired behavior.)

like image 81
Sirko Avatar answered Jan 21 '26 10:01

Sirko


Why do you need a for loop? I think this should suffice:

 if ( response.d.length > imagesPerPage ) 
 {
   alert('more');
 }
 else
 {
   alert('less');
 }
like image 29
Mithrandir Avatar answered Jan 21 '26 10:01

Mithrandir