Trying to write a fizzBuzz quiz to generate the word "fizz"
for any number in an array divisible by 5, and the word "Buzz"
for number divisible by 3 and lastly "fizzBuzz"
for number divisible by 5 and 3 using the chrome JavaScript console.
This code just prints the numbers without replacing them with the word fizz and Buzz.
I’m expected to keep entering the function fizzBuzz()
in the console, so as to keep generating other numbers, my question is, why isn’t working?.
I expected result like:
[1,2,"Buzz",4,"Fizz","Buzz",7,8,"Buzz","Fizz",11,"Buzz",13,14,"FizzBuzz"]
But instead I get:
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
This is my current code:
var output=[];
var previous = 1;
function fizzBuzz(){
if (output[(previous-1)]%5===0 && output[(previous-1)]%3===0){
output.push(("FizzBuzz"));
console.log(output);
previous++;
}
else if (output[(previous-1)]%5===0){
output.push("Fizz");
console.log(output);
previous++;
}
else if (output[(previous-1)]%3===0){
output.push("Buzz");
console.log(output);
previous++;
}
else {
output.push(previous);
console.log(output);
previous++;
}
}
4
Answers
So after checking your advices i change my algorithm and this one works,
An easier approach to achieve the same result without declaring additional variables is by mutating the original array.
How about using a generator function instead of keeping global variables! For instance
or maybe a closure that behaves like a generator
You can check this out 😀