当前位置: 动力学知识库 > 问答 > 编程问答 >

loops - How can I improve this JavaScript code?

问题描述:

for(var i = 1; i <= 20; i++){

switch (i) {

case 3:

case 6:

case 9:

case 12:

case 18:

console.log("Fizz");

break;

case 5:

case 10:

case 20:

console.log("Buzz");

break;

case 15:

console.log("FizzBuzz");

break;

default:

console.log(i);

}

}

I am supposed to print numbers from 1-20.

These are the conditions.

if a number is divisible by 3, then i need to print "Fizz"

If a number is divisible by 5, then I need to print "Buzz"

if a number is divisible by both 3 and 5, then I need to print "FizzBuzz".

I came up with the aforementioned code, but I think it can be improved.

网友答案:

You can use the modulus operator (%), this will help make your code future proof, should the 20 need to change to 200 etc

for(var i = 1; i <= 20; i++){
    if(i % 5  == 0 && i % 3  == 0) {
        console.log("FizzBuzz");
    } else if (i % 3 == 0) {
        console.log("Fizz");
    } else if (i % 5  == 0) {
        console.log("Buzz");
    } else {
        console.log(i);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: