skip to Main Content

Below is my code so far. My console.log is printing the array in sequential numbers each time I run the function. I want "fizz" to be printed when count%3===0, which it’s doing, but also adding 3 to the array. I want the array to look like this [1, 2, "fizz", 4, 5, "fizz", ].

var output = [];
var count = 1
function fizzBuzz(){
output.push(count);
count++;

console.log(output);

if (count % 3 == 0){ 
 output.push("fizz");
}

2

Answers


  1. modify your code with this

    var output = [];
    var count = 1;
    function fizzBuzz() {
      if (count % 3 == 0) {
        output.push("fizz");
      } else {
        output.push(count);
      }
      count++;
      console.log(output);
    }
    
    Login or Signup to reply.
  2. Not sure what you expect so here are two solutions :

            var output1 = [];
            var count1 = 0;
            
            function fizzBuzz(){
                count1++;
                if (count1 % 3 == 0){ 
                    output1.push("fizz");
                }else{
                    output1.push(count1);
                }
            }
            
            var output2 = [];
            var count2 = 0;
            
            function fooBuzz(){
                count2++;
                if (count2 % 3 == 0){ 
                    output2.push(count2);
                    output2.push("foo");
                }else{
                    output2.push(count2);
                }
            }
            
            for(var i = 0; i<6; i++){
                fizzBuzz();
            }
            for(var j = 0; j<6; j++){
                fooBuzz();
            }
            console.log(output1);
      /* output
    [
      1,
      2,
      "fizz",
      4,
      5,
      "fizz"
    ]
    */
            console.log(output2);
    /* output
    [
      1,
      2,
      3,
      "foo",
      4,
      5,
      6,
      "foo"
    ]
    */
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search