JavaScript loop if statement by 5s - Stack Overflow

I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's a

I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's an easier way than writing all those numbers out.

for (i = 1; i <= 500; i++){
    var loopCheck = i === 5 || i === 10 || i === 15 || i === 20 || i === 25;
    if (loopCheck === true){
        alert("if statement works!!!"):
    }

}

I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's an easier way than writing all those numbers out.

for (i = 1; i <= 500; i++){
    var loopCheck = i === 5 || i === 10 || i === 15 || i === 20 || i === 25;
    if (loopCheck === true){
        alert("if statement works!!!"):
    }

}
Share Improve this question edited Jan 18, 2015 at 19:42 Oleg 9,3692 gold badges45 silver badges59 bronze badges asked Jan 18, 2015 at 19:38 MattMatt 1731 silver badge14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

For the sake of being different:

You can use the modulo % operator:

for (i = 1; i <= 500; i++) {
  if (i % 5 === 0) { // if `i` is *perfectly* divisible by 5
    // do something here
  }
}

Just add 5 to i on each iteration:

for (i = 5; i <= 500; i += 5) {
    // ...
}

i += 5 is shorthand for i = i + 5. Note that we start with i set to 5 here.

I agree with the simplicity Bens answer, as an alternative, you can use modulo:

for (var i = 1; i <= 500; i++){
   if (i%5 === 0) {
        console.log(i);
    }
}

That maintains the "looping through every number" but with modulo you ask "when I divide the number by 5, what remainder do I have?" If its divisible by 5, you have a remainder of 0. :)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745431735a4627421.html

相关推荐

  • JavaScript loop if statement by 5s - Stack Overflow

    I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's a

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信