javascript fizzbuzz switch statement

前端 未结 8 721
慢半拍i
慢半拍i 2021-01-18 00:13

I\'m currently taking the code academy course on Javascript and I\'m stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by

8条回答
  •  青春惊慌失措
    2021-01-18 00:36

    The switch(true) part of this statement helped me. I was trying to do a switch statement for fizzbuzz. My solution incorporates the coding style of Rosettacodes - general solution. Most significantly the use of force typing to shorten the primary conditionals. I thought, it was valuable enough to post:

    var fizzBuzzSwitch = function() {
      for (var i =0; i < 101; i++){
        switch(true) {
          case ( !(i % 3) && !(i % 5) ):
            console.log('FizzBuzz');
            break;
          case ( !(i % 3) ):
            console.log('Fizz');
            break;
          case ( !(i % 5) ):
           console.log('Buzz');
           break;
          default:
           console.log(i);
        }
      }
    }
    

提交回复
热议问题