javascript fizzbuzz switch statement

前端 未结 8 701
慢半拍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:41

    Switch matches the x in switch(x){ to the result of evaluating the case expressions. since all your cases will result in true /false there is no match and hence default is executed always.

    now using switch for your problem is not recommended because in case of too many expressions there may be multiple true outputs thus giving us unexpected results. But if you are hell bent on it :

    for (var x = 0; x <= 20; x++) {
      switch (true) {
        case (x % 5 === 0 && x % 3 === 0):
            console.log("FizzBuzz");
            break;
        case x % 3 === 0:
            console.log("Fizz");
            break;
        case x % 5 === 0:
            console.log("Buzz");
            break;
        default:
            console.log(x);
            break;
      }
    

    }

提交回复
热议问题