javascript fizzbuzz switch 语句

2022-01-19 00:00:00 switch-statement javascript fizzbuzz

我目前正在学习关于 Javascript 的代码学院课程,但我被困在 FizzBu​​zz 任务上.我需要从 1 到 20 数,如果该数字可被 3 个打印嘶嘶声、5 个打印嗡嗡声整除,则由两个打印嘶嘶声整除,否则只打印数字.我可以用 if/else if 语句来做到这一点,但我想用 switch 语句来尝试它,但无法得到它.我的控制台只记录默认值并打印 1-20.有什么建议?

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 5 print buzz, by both print fizzbuzz, else just print the number. I was able to do it with if/ else if statements, but I wanted to try it with switch statements, and cannot get it. My console just logs the default and prints 1-20. Any suggestions?

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


};

推荐答案

Switch 将 switch(x){ 中的 x 匹配到 case 表达式的计算结果.因为你所有的情况都会导致 true/false 没有匹配,因此默认总是执行.

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.

现在不建议使用 switch 来解决您的问题,因为如果表达式过多,可能会有多个 true 输出,从而给我们带来意想不到的结果.但是,如果您一心想要:

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;
  }

}

相关文章