区分循环中的两个不同动作

时间:2015-05-16 12:35:42

标签: javascript if-statement modulo

我正在尝试做这样的事情

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

问题是他总是进入else循环。 有人知道为什么吗?

2 个答案:

答案 0 :(得分:2)

因为1 % 2 === 0返回false

你可能想把它放在循环中

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

答案 1 :(得分:1)

单步执行代码:

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

如果您想将其置于循环中,请参阅@ DryrandzFamador的答案。