最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Eloquent Javascript FizzBuzz - Stack Overflow

programmeradmin6浏览0评论

I'm currently working through eloquent javascript.

I'm trying to do the fizzbuzz task, I'm struggling when having to print numbers divisible by 3 & 5.

Task and my solution so far below.

Cheers.

Task:

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those). (This is actually an interview question that has be

My solution:

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

I'm currently working through eloquent javascript.

I'm trying to do the fizzbuzz task, I'm struggling when having to print numbers divisible by 3 & 5.

Task and my solution so far below.

Cheers.

Task:

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those). (This is actually an interview question that has be

My solution:

for(i=1; i<101; i++) {
    if(i % 3 === 0) {
        console.log("Fizz");
    } else if(i % 5 === 0) {
        console.log("Buzz");
    } else if (i % 3 === 0 && i % 5 === 0){
        console.log("FizzBuzz");
    } else {
        console.log("What should this be?");
    }
}
Share Improve this question asked Nov 6, 2016 at 9:35 Joe ConsterdineJoe Consterdine 1,0532 gold badges20 silver badges41 bronze badges 2
  • 2 Possible duplicate of FizzBuzz program(details given) in Javascript – Boghyon Hoffmann Commented Nov 8, 2017 at 9:25
  • The origin of this problem: Using FizzBuzz to Find Developers who Grok Coding. – Adam Millerchip Commented Jan 31, 2022 at 7:26
Add a comment  | 

13 Answers 13

Reset to default 9

Your code would never reach the block inside else if (i % 3 === 0 && i % 5 === 0) because either if (i % 3 === 0) or else if (i % 5 === 0) would be true first.

Here's maybe an easier way to think about this problem:

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

NOTE: please don't do this in production code!

You could even do it with an ES6 one-liner (broken on multple lines for "clarity").

console.log(
  [...Array(100).keys()].map((_, i) => i + 1)
                        .map(
                            i => (
                                    (i % 3 === 0 ? "Fizz" : "")
                                  + (i % 5 === 0 ? "Buzz" : "")
                                 ) || i
                        )
                        .join("\n")
);

here is the break-down of the various parts:

[...Array(100).keys()]

creates an empty array of length 100, and returns its keys, which are then used to build a new array, so we get [0 ... 99]

.map((_, i) => i + 1)

this replaces each element with its index incremented by 1, so we now have [1 ... 100]

.map(i => ...)

now we apply FizzBuzz logic, by testing all the possible combinations in the correct order, using the ternary operator

.join("\n");

and finally we join the result as a single string separated with newlines.

Your conditions were in the wrong order:

for(i=1; i<101; 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("What should this be?");
    }
}

03-26-2022

New answer based on idea provided by Danny '365CSI' Engelman.
His version was indeed faster but a combo of his array fill method and my early return function beats us both (at least in Chrome).

const fizzBuzz = (n) => {
  if (n % 15 === 0) return 'FizzBuzz';
  if (n % 3 === 0) return 'Fizz';
  if (n % 5 === 0) return 'Buzz';
  return n;
};

const arr = Array(100)
  .fill(fizzBuzz)
  .map((func, i) => func(i + 1));

console.log(arr.join(', '));



Old Answer

Succinct, functional & fast. I'm not sure it gets more eloquent than this.

const oneToOneHundred = Array.from({ length: 100 }, (_, i) => i + 1);

const fizzBuzz = (n) => {
  if (n % 15 === 0) return 'FizzBuzz';
  if (n % 3 === 0) return 'Fizz';
  if (n % 5 === 0) return 'Buzz';
  return n;
};

const arr = oneToOneHundred.map((i) => fizzBuzz(i));

console.log(arr.join(', '));

let arr = Array(100)
  .fill((x, div, label) => x % div ? "" : label) //store Function in every index
  .map((func, idx) =>
    func(++idx, 3, "Fizz") + func(idx, 5, "Buzz") || idx
  );
document.body.append(arr.join(", "));

fill takes a single Object, it is not executed 100 times!
Since JavaScript Functions are Objects this code declares a function once

Note the ++idx because we want to start at 1, not 0

In JavaScript ""+"" is a Falsy value, thus it returns the idx value for non-FizzBuzz numbers

More Array Methods explained: https://array-methods.github.io

Update

  • maintainable
  • extendible
  • translatable
  • performant

let arr = Array(100)
  .fill( { three: "Fizz", five: "Buzz" })
  .map(( { three,five }, idx) => {
    idx++;
    if (idx % 15 == 0) return three + five;
    if (idx % 3 == 0) return three;
    if (idx % 5 == 0) return five;
    return idx;
  });
console.log(arr.join(", "));

Use the following code

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

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

  • create a result variable
  • append Fizz if it is even divisible by 3
  • append Buzz if it is even divisible by 5
  • if result === "" log i
    • otherwise log result
  • result resets to "" at the start of each loop

Search for "fizzbuzz golf" to see the shortest solutions possible in a variety of languages.

function PrintFizzBuzz(){

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

This is my answer:

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

The solutions to FizzBuzz that append to an output string are eloquent but are a bit inflexible (e.g. if the problem is changed to require different outputs).

This solution avoids appending, and uses nested shorthand conditionals for brevity:

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

var nums = [];
var index = 0;
var x = 0;
while(nums.length <= 100){
    nums.push(index);
    index++;
}
for(x;x < nums.length;x++){
    if(nums[x] % 5 == 0 && nums[x] % 3 != 0){
        
        nums[x] = "buzz";
    }
    if(nums[x] % 3 == 0 && nums[x] % 5 != 0){
        nums[x] = "fizz";

    }
    if(nums[x] % 5 == 0 && nums[x] % 5 == 0){
        nums[x] = "fizzbuzz";

    }
    console.log(nums[x]);
}
<html>
    <head>
        <title>question</title>
        <script src="sketch.js"></script>
    </head>
    <body>
        
    </body>
</html>

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

for (i = 1; i < 101; i++) {
  if (i % (3 * 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);
}

}

发布评论

评论列表(0)

  1. 暂无评论