简体   繁体   中英

fizzBuzz count++ doesn't work in if/else statement

var output = []; 
var count = 1;

function fizzBuzz() {

    if (count % 5 === 0 && count % 3 === 0) {
        output.push("FizzBuzz");
    } else if (count % 5 === 0) {
        output.push("Buzz");
    } else if (count % 3 === 0) {
        output.push("Fizz");
    } else {
        output.push(count++;);
      
    }
//count++;//
    
  console.log(output);
    
}

count++ does not work in else statement. How ever if I take it out from else statement and put count into else it works. Why is the reason?

To fix the bug, you can simply move the count++; statement to the end of the function, like this:

function fizzBuzz() {
if (count % 5 === 0 && count % 3 === 0) {
    output.push("FizzBuzz");
} else if (count % 5 === 0) {
    output.push("Buzz");
} else if (count % 3 === 0) {
    output.push("Fizz");
} else {
    output.push(count);
}
count++;
console.log(output);}

There is a bug in the code that is causing the count variable to not be incremented at the end of each iteration. This means that the function will only ever process the first number and then stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM