Javascript中的FizzBu​​zz程序(详细说明)

前端之家收集整理的这篇文章主要介绍了Javascript中的FizzBu​​zz程序(详细说明)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以为FizzBu​​zz更正我的这段代码吗?似乎有一个小错误.下面的代码打印所有数字,而不是仅打印不能被3或5整除的数字.

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".

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")
  }
}

解决方法

/*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);

无论如何,您的函数都会返回虚假值,但无论如何都会打印.不需要让这个过于复杂.

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

原文链接:https://www.f2er.com/js/156556.html

猜你在找的JavaScript相关文章