该语句返回1-100之间的所有数字,但未应用嘶嘶声规则。不知道为什么。你能提供一个解释吗?

for (var number = 1; number <= 100; number++) {
  switch(number) {
  case number % 3 == 0:
    console.log('Fizz');
    break;
  case number % 5 == 0:
    console.log('Buzz');
    break;
  case number % 5 == 0 && number % 3 == 0:
    console.log('FizzBuzz');
    break;
  default:
    console.log(number);
    break;
  }
}

最佳答案

您正在将数字与布尔表达式进行比较。该开关将等效于:

if (number == (number % 3 == 0)) {
  console.log('Fizz');
} else if (number == (number % 5 == 0)) {
  console.log('Buzz');
} else if (number == (number % 5 == 0 && number % 3 == 0)) {
  console.log('FizzBuzz');
} else {
  console.log(number);
}


使用if语句代替开关,并首先检查double条件:

if (number % 5 == 0 && number % 3 == 0) {
  console.log('FizzBuzz');
} else if (number % 3 == 0) {
  console.log('Fizz');
} else if (number % 5 == 0) {
  console.log('Buzz');
} else {
  console.log(number);
}

09-25 16:10