📜  fizzbuzz javascript (1)

📅  最后修改于: 2023-12-03 15:15:05.518000             🧑  作者: Mango

FizzBuzz in JavaScript

FizzBuzz is a popular programming question often asked during interviews. The problem requires the programmer to print out numbers from 1 to n, but with the following modifications:

  • If the number is divisible by 3, print out "Fizz"
  • If the number is divisible by 5, print out "Buzz"
  • If the number is divisible by both 3 and 5, print out "FizzBuzz"

Let's take a look at how we can solve this problem in JavaScript.

If-else approach

One way to solve FizzBuzz is to use if-else statements.

for (let i = 1; i <= n; 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);
  }
}

This code uses a for loop to iterate through numbers from 1 to n. It then checks if each number satisfies any of the three conditions described earlier. If so, it prints out the corresponding string. Otherwise, it prints out the number itself.

Ternary operator approach

Another way to solve FizzBuzz is to use the ternary operator.

for (let i = 1; i <= n; i++) {
  const fizz = i % 3 === 0 ? "Fizz" : "";
  const buzz = i % 5 === 0 ? "Buzz" : "";
  console.log(fizz + buzz || i);
}

This code also uses a for loop to iterate through numbers from 1 to n. It uses the ternary operator to check if each number is divisible by 3 and/or 5. It then concatenates corresponding strings and prints out either the concatenated string or the number itself.

Conclusion

FizzBuzz is a simple problem that can be solved using various approaches in JavaScript. The most important thing is to think logically and use the language features to your advantage.