最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript loop if statement by 5s - Stack Overflow

programmeradmin1浏览0评论

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. :)

发布评论

评论列表(0)

  1. 暂无评论