Javascript 中的 FizzBu​​zz 程序(已给出详细信息)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16620665/
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-27 05:22:46  来源:igfitidea点击:

FizzBuzz program (details given) in Javascript

javascriptfizzbuzz

提问by pacmanfordinner

Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.

有人可以为FizzBu​​zz更正我的这段代码吗?似乎有一个小错误。下面的代码打印所有数字,而不是仅打印不能被 3 或 5 整除的数字。

Write a program that prints the numbers from 1to 100. But for multiples of three, print "Fizz"instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

编写一个程序,打印从1到的数字100。但是对于三的倍数,打印"Fizz"而不是数字,对于五的倍数,打印"Buzz"。对于既是三又是五的倍数的数字,打印"FizzBuzz"

function isDivisible(numa, num) {
  if (numa % num == 0) {
    return true;
  } else {
    return false;
  }
};

function by3(num) {
  if (isDivisible(num, 3)) {
    console.log("Fizz");
  } else {
    return false;
  }
};

function by5(num) {
  if (isDivisible(num, 5)) {
    console.log("Buzz");
  } else {
    return false;
  }
};

for (var a=1; a<=100; a++) {
  if (by3(a)) {
    by3(a);
    if (by5(a)) {
      by5(a);
      console.log("\n");
    } else {
      console.log("\n");
    }
  } else if (by5(a)) {
    by5(a);
    console.log("\n");
  } else {
    console.log(a+"\n")
  }
}

采纳答案by Ben McCormick

/*Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”*/

var str="",x,y,a;
for (a=1;a<=100;a++)
{
    x = a%3 ==0;
    y = a%5 ==0;
    if(x)
    {
        str+="fizz"
    }
    if (y)
    {
        str+="buzz"
    }
    if (!(x||y))
    {
        str+=a;
    }
    str+="\n"
}
console.log(str);

Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.

无论如何,您的函数都会返回假值,但无论如何都会打印。没有必要使这过于复杂。

fiddle: http://jsfiddle.net/ben336/7c9KN/

小提琴:http: //jsfiddle.net/ben336/7c9KN/

回答by Trevor Dixon

for (let i = 1; i <= 100; i++) {
    let out = '';
    if (i % 3 === 0) out += 'Fizz';
    if (i % 5 === 0) out += 'Buzz';
    console.log(out || i);
}

回答by Noctis

Was fooling around with FizzBuzz and JavaScript as comparison to C#.

将 FizzBu​​zz 和 JavaScript 与 C# 进行比较。

Here's my version, heavily influenced by more rigidlanguages:

这是我的版本,受更多rigid语言的影响很大:

function FizzBuzz(aTarget) {
    for (var i = 1; i <= aTarget; i++) {
        var result = "";
        if (i%3 === 0) result += "Fizz";        
        if (i%5 === 0) result += "Buzz";
        if (result.length ===0) result = i;

        console.log(result);
    }
}

I like the structure and ease of read.

我喜欢它的结构和易于阅读。

Now, what Trevor Dixoncleverly did is relay on the false-y values of the language (false, null, undefined, ''(the empty string) , 0and NaN(Not a Number)) to shorten the code.
Now, the if (result.length ===0) result = i;line is redundant and the code will look like:

现在,特雷弗·迪克森 (Trevor Dixon)聪明地做的是中继语言的假 y 值 ( false, null, undefined, ''(空字符串)0NaN(Not a Number)) 以缩短代码。
现在,该if (result.length ===0) result = i;行是多余的,代码将如下所示:

function FizzBuzz(aTarget) {
    for (var i = 1; i <= aTarget; i++) {
        var result = "";
        if (i%3 === 0) result += "Fizz";        
        if (i%5 === 0) result += "Buzz";

        console.log(result || i);
    }
}

Here we relay on the ||operator to say : "if resultis false, print the iteration value (i)". Cool trick, and I guess I need to play more with JavaScript in order to assimilate this logic.

在这里,我们传递||操作符说:“如果result为假,则打印迭代值 ( i)”。很酷的技巧,我想我需要更多地使用 JavaScript 来吸收这个逻辑。

You can see other examples (from GitHub) that will range from things like :

您可以看到其他示例(来自GitHub),包括以下内容:

for (var i=1; i <= 20; i++)
{
    if (i % 15 == 0)
        console.log("FizzBuzz");
    else if (i % 3 == 0)
        console.log("Fizz");
    else if (i % 5 == 0)
        console.log("Buzz");
    else
        console.log(i);
}

No variables here, and just check for division by 15,3 & 5 (my above one only divides by 3 & 5, but has an extra variable, so I guess it's down to microbenchmarking for those who care, or style preferences).

这里没有变量,只需检查除以 15,3 和 5(我上面的那个只除以 3 和 5,但有一个额外的变量,所以我想这取决于对那些关心或风格偏好的人的微基准测试)。

To:

到:

for(i=0;i<100;)console.log((++i%3?'':'Fizz')+(i%5?'':'Buzz')||i)

Which does it all in on line, relaying on the fact that 0is a false value, so you can use that for the if-elseshorthanded version (? :), in addition to the ||trick we've seen before.

这一切都在网上完成,中继0一个错误值的事实,因此除了我们之前看到的技巧之外,您还可以将其用于if-else简写版本 ( ? :) ||

Here's a more readable version of the above, with some variables:

这是上述内容的可读性更强的版本,其中包含一些变量:

for (var i = 1; i <= 100; i++) {
  var f = i % 3 == 0, b = i % 5 == 0;
  console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}

All in all, you can do it in different ways, and I hope you picked up some nifty tips for use in JavaScript :)

总而言之,你可以用不同的方式来完成,我希望你能学到一些在 JavaScript 中使用的技巧:)

回答by Pavan Varanasi

With ternary operator it is much simple:

使用三元运算符很简单:

    for (var i = 0; i <= 100; i++) {
      str = (i % 5 == 0 && i % 3 == 0) ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0) ? "Buzz" : i);
      console.log(str);
    }

回答by Kaneiba

for(i = 1; i < 101; i++) {  
  if(i % 3 === 0) {
      if(i % 5 === 0) {
          console.log("FizzBuzz");
      }
      else {
          console.log("Fizz");
      }
  }
  else if(i % 5 === 0) {
      console.log("Buzz");
  }
  else {
      console.log(i)
  }
}

回答by icktoofay

In your by3and by5functions, you implicitly return undefinedif it is applicable and falseif it's not applicable, but your ifstatement is testing as if it returned trueor false. Return trueexplicitly if it is applicable so your ifstatement picks it up.

在您的by3by5函数中,undefined如果适用和false不适用,您会隐式返回,但是您的if语句正在测试,就好像它返回true或 一样falsetrue如果适用,则明确返回,以便您的if陈述将其选中。

回答by Matt Murphy

Codeacademy sprang a FizzBuzz on me tonight. I had a vague memory that it was "a thing" so I did this. Not the best way, perhaps, but different from the above:

Codeacademy 今晚向我发出了 FizzBu​​zz。我有一个模糊的记忆,它是“一件事”,所以我这样做了。也许不是最好的方法,但与上述不同:

var data = {
    Fizz:3,
    Buzz:5
};

for (var i=1;i<=100;i++) {
    var value = '';
    for (var k in data) {
        value += i%data[k]?'':k;
    }
    console.log(value?value:i);
}

It relies on data rather than code. I think that if there is an advantage to this approach, it is that you can go FizzBuzzBing 3 5 7 or further without adding additional logic, provided that you assign the object elements in the order your rules specify. For example:

它依赖于数据而不是代码。我认为,如果这种方法有一个优势,那就是您可以在不添加额外逻辑的情况下继续 FizzBu​​zzBing 3 5 7 或进一步,前提是您按照规则指定的顺序分配对象元素。例如:

var data = {
    Fizz:3,
    Buzz:5,
    Bing:7,
    Boom:11,
    Zing:13
};

for (var i=1;i<=1000;i++) {
    var value = '';
    for (var k in data) {
        value += i%data[k]?'':k;
    }
    console.log(value?value:i);
}

回答by Wildhoney

As an ES6 generator: http://www.es6fiddle.net/i9lhnt2v/

作为 ES6 生成器:http: //www.es6fiddle.net/i9lhnt2v/

function* FizzBuzz() {

    let index = 0;

    while (true) {

        let value = ''; index++;

        if (index % 3 === 0) value += 'Fizz';
        if (index % 5 === 0) value += 'Buzz';

        yield value || index;

    }

}

let fb = FizzBuzz();
for (let index = 0; index < 100; index++) {
    console.log(fb.next().value);
}

回答by Mutant

This is what I wrote:

这是我写的:

for (var num = 1; num<101; num = num + 1) {
    if (num % 5 == 0 && num % 3 == 0) {
        console.log("FizzBuzz");
    }
    else if (num % 5 == 0) {
        console.log("Buzz");
    }
    else if (num % 3 == 0) {
        console.log("Fizz");
    }
    else {
        console.log(num);
    }
}

回答by Mahmut G

for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz");
    else if (i%3 === 0) console.log("Fizz");    
    else if (i%5 === 0) console.log("Buzz");    
    else console.log(i);    
}

One of the easiest way to FizzBuzz. Multiple of 3 and 5, at the same time, means multiple of 15.

FizzBu​​zz 最简单的方法之一。3 和 5 的倍数同时表示 15 的倍数。

Second version:

第二个版本:

for (var i = 1; i <= 100; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i%3 === 0) console.log("Fizz");    
    else if (i%5 === 0) console.log("Buzz");    
    else console.log(i);    
}