I'm creating a simple Javascript Function that should write the numbers from 1 to n. For any multiplier of 3, it outputs "Fizz", instead of multiplers of 5 you output "Buzz", and if they happen at the same time, you should use "FizzBuzz". The output of the function should be a mixed array of numbers and strings.
My current code is outputting the array order and expected values incorrectly.
function fizzbuzz (n) {
let arr = [];
for (let i = 0; i < n; i++){
//if i is a multiple of 3 then Fizz
if(i % 3 === 0) {
arr.push("Fizz");
}
//if i is a multiple of 5 then Buz
if(i % 5 == 0) {
arr.push("Buzz");
}
//if both then FizzBuzz
if(i % 3 === 0 && i % 5 === 0) {
arr.push("FizzBuzz");
}
else {
arr.push(i);
}
}
return arr;
}
When fizzbuzz(7) is entered, I expect the output to look like this:
[0, 1, 2, "Fizz", 4, "Buzz", "Fizz", 7];
Instead, it's this:
["Fizz","Buzz","FizzBuzz",1,2,"Fizz",3,4,"Buzz",5,"Fizz",6]
Could someone enlighten me to the fault in my logic? This should be more straightforward than I had originally thought.
You have three different
ifstatements there, the last one having anelseclause, instead of one continuousifstatement with severalelse ifclauses. Note that for this to work properly you need to first test the "FizzBuzz" condition:Quick note regarding the expected output - 0 is divisible by 3 and 5 (and other other integer, for that matter), so the first element of the array should be "FizzBuzz"