简体   繁体   中英

Differentiate between two different actions in loop

I am trying to do something like this

var teller = 1;
if (teller % 2 === 0) {
  "do this"
} else {
  "do something else"
}
teller++;

The problem is that he always comes into the else loop. Someone knows why?

because 1 % 2 === 0 returns false

you might want to put it inside a loop

var teller = 1;
while(teller < 100){ //100 is the range, just a sample
    if (teller % 2 === 0) {
         "do this"
    } else {
          "do something else"
    }
    teller++;
}

Stepping through your code:

var teller = 1;          //teller is now 1
if (teller % 2 === 0) {  //1 % 2 === 1, so this statement is skipped
  "do this"
} else {                 //since the if statement was skipped, this gets run
  "do something else"
}
teller++;                //this has no affect on the above

If you want to put this in a loop, see @DryrandzFamador's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM