为什么没有打印出fizzbuzz?

时间:2016-02-05 23:08:31

标签: javascript fizzbuzz

这是我的代码。我没有打印出任何Fizz的嗡嗡声。我只得到数字。谁有人解释为什么?感谢

printOut = ""; 

for (var x=1; x < 101 ; x++) {


  switch(x) {

      case((x%3) == 0):
      printOut+="\n"+ "Fizz" ;
      break;

      case((x%5) == 0):
      printOut+="\nBuzz";
      break;

      default:
      printOut+="\n" + x ;
      break;

  }

}
console.log(printOut);

3 个答案:

答案 0 :(得分:3)

检查您如何使用switch语句:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

切换线x中的

是你的表达式,((x%5)== 0)是你的值。我认为你的意思是少数if / else语句。

答案 1 :(得分:0)

您未正确使用switch语句。每当case (value):等于x时,每个value基本上都应该运行。

要解决此问题,只需完全删除switch语句,并为每个if替换case

for (var x = 1; x < 101; x++) {
    if ((x % 3) == 0)
        printOut += "\n" + "Fizz";
    else if ((x % 5) == 0)
        printOut += "\nBuzz";
    else
        printOut += "\n" + x;
}

答案 2 :(得分:0)

您尝试将x的值与值为truefalse的表达式进行匹配。您可以在交换机中传递true,并且交换机将与第一个评估为true的case语句“匹配”。

虽然这种方式有效,但我建议只做if / else语句。这对于数字30不起作用,对于X%3和x%5都是True。它将首先与x%3匹配并停在那里。

printOut = ""; 

for (var x=1; x < 101 ; x++) {


  switch(true) {

      case((x%3) == 0):
      printOut+="\n"+ "Fizz" ;
      break;

      case((x%5) == 0):
      printOut+="\nBuzz";
      break;

      default:
      printOut+="\n" + x ;
      break;

  }

                             }
console.log(printOut);
相关问题