javascript fizzbuzz switch statement

前端 未结 8 711
慢半拍i
慢半拍i 2021-01-18 00:13

I\'m currently taking the code academy course on Javascript and I\'m stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by

8条回答
  •  死守一世寂寞
    2021-01-18 00:29

    Switch statement checks if the situation given in the cases matches the switch expression. What your code does is to compare whether x divided by 3 or 5 is equal to x which is always false and therefore the default is always executed. If you really want to use a switch statement here is one way you can do.

    for (var i=1; i<=30; i++){
      switch(0){
        case (i % 15):
          console.log("fizzbuzz");
          break;
        case (i % 3):
          console.log("fizz");
          break;
        case (i % 5):
          console.log("buzz");
          break;
        default:
          console.log(i);
      }
    }
    

提交回复
热议问题