javascript 判断一个数是否能被 3 或 5 整除 (FizzBu​​zz)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31106668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:17:14  来源:igfitidea点击:

Find if a number is divisible by 3 or 5 (FizzBuzz)

javascriptfizzbuzz

提问by Corey Blinks

How do I change the output depending on whether or not it is divisible by 3 or 5? If it is divisible by 3, I want to show "rock" and if it's divisible by 5 I want to show "star" (similar to in FizzBuzz). If both, they'll see both.

如何根据输出是否可被 3 或 5 整除来更改输出?如果它可以被 3 整除,我想显示“rock”,如果它可以被 5 整除,我想显示“star”(类似于在 FizzBu​​zz 中)。如果两者都有,他们就会看到。

Here's my code:

这是我的代码:

if (var n = Math.floor((Math.random() * 1000) + 1); {
  var output = "";
  if (n % 3 == 0)
    output += "Rock";
  if (n % 5 == 0)
    output += "star";
  prompt(output || n);
}

Why isn't my code working properly?

为什么我的代码不能正常工作?

回答by Burning Crystals

var n = Math.floor((Math.random() * 1000) + 1);
if (n) {
  var output = "";
  if (n % 3 == 0)
    output += "Rock";
  if (n % 5 == 0)
    output += "star";
  prompt(output || n);
}

The varinside the ifstatement is a syntax error. My browser shows this error:

var里面if的语句是一个语法错误。我的浏览器显示此错误:

SyntaxError: expected expression, got keyword 'var'

So I think you should declare variable nbefore telling the ifstatement that var nis your comparison expression.

所以我认为你应该n在告诉你的比较表达式的if语句之前声明变量var n