!(非)运算符在切换情况下的用法

问题描述 投票:0回答:3

// checking whether a number is a multiple of 3 or not 
for (let number = 1; number <= 100; number++) {
  switch (number % 3) {
    case !0: // Here I have used !(not) but it's not helping, I only want to know why '!' is not helping           
      console.log(`${number} is not multiple of 3`);
      break;

    default:
      console.log(`${number} is multiple of 3`)
  }
}

这里第一种情况不起作用。代码执行没有问题,但是第一种情况根本没有帮助。整个流程仅转到“默认值:”代码块。每当余数不等于0时,都应执行第一种情况的代码块,但始终会转到默认代码块。

javascript switch-statement operator-keyword not-operator
3个回答
1
投票

您不能以这种方式进行操作,因为!0在JavaScript中始终为true,因此循环总是在第一种情况下进入

以这种方式尝试

for (let number = 1; number <= 100 ;number++ ) {
  if(number % 3){
    console.log(`${number} is not multiple of 3`); 
  }
  else{
    console.log(`${number} is multiple of 3`); 
  }
}

0
投票

[!0等于true,不等于12

考虑以这种方式编写:

for (let number = 1; number <= 100; number++) {
	switch (number % 3) {
		case 0:
			console.log(`${number} is multiple of 3`)
			break;
		default:
			console.log(`${number} is not multiple of 3`);
	}
}

0
投票

在JS中,将0视为falsy,这就是!0等于true(不是falsy)的原因。

关于您的开关,您可以反向它,并使用true作为开关值。然后,这些案例将具有要检查的表达式

for (let number = 1; number <= 100 ;number++ ) {
   switch (true) {
     case number % 3:        
         console.log(`${number} is not multiple of 3`); 
     break;

     default:
         console.log(`${number} is multiple of 3`)
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.