javascript fizzbuzz switch 语句

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

问题描述

我目前正在学习关于 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;
  }

}

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)