为什么 mod (%) 计算结果为零不会在 JavaScript 条件评估中被视为虚假


if (!5%5) {
  console.log('its a 5%!');
}
if (5%5 === 0) {
  console.log('its a 5%! but eval differently');
}

https://codepen.io/adamchenwei/pen/ZXNraK?editors=0010

像上面这样的东西,你只会看到第二个陈述来评估为真。为什么?不是第一个语句!帮助将值恢复为 true。我错过了什么?

!50

0 % 5是假的。

因此,您的 if 不会触发。

表达式 !5%5 被解释为(!5)%5括号。换句话说,!算子绑定得非常紧密,因此!5先于%算子进行评估

考虑一个表达式,例如 -x+y . 显然,这意味着(-x)+y,而不是-(x+y),因为传统的算术运算符优先规则。!运算符在这方面类似于一元-

表达式 !500%5 是 0,所以!5%5不是"真"。

这是因为5%5的结果不是数字(NaN),你不能反转它。但是,如果您将此结果存储到变量中,或者将5%5括在括号中(这将更改执行顺序),则可以在尝试时使用它。下面是一些行,它们应该可以帮助您了解行为:

var result = 5%5;
if (!result) {
  console.log('Works with variable');
}
if (!5%5) {
  console.log('Works without variable');
} else {
  console.log('!5%5 evaluates to "!NaN"');
}
if (!(5%5)) {
  console.log('!(5%5) works with parentheses');
} else {
  console.log('!(5%5) doesn't work');
}
console.log("The type of 5%5 is: ", typeof 5%5);
console.log("The type of (5%5) is: ", typeof (5%5));
console.log("The type of 5%5 stored in variable is: ", typeof result);
console.log("The type of !(5%5) is: ", typeof !(5%5));

最新更新