javascript fizzbuzz switch语句 [英] javascript fizzbuzz switch statement

查看:95
本文介绍了javascript fizzbuzz switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在接受关于Javascript的代码学院课程,但我仍然坚持使用FizzBu​​zz任务。我需要从1-20计算,如果数字可以被3个打印嘶嘶声,5个打印嗡嗡声,可以被两个打印fizzbuzz整除,否则只需打印数字。我能用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匹配评估案例表达的结果。因为所有情况都会导致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来解决你的问题,因为如果表达式太多,可能会有多个真正的输出,从而给我们带来意想不到的结果。但是,如果你对此很感兴趣:

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

}

这篇关于javascript fizzbuzz switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆