【问题标题】:Why does the if - block >>>> if(!variable) <<<<< get executed when variable = 0?为什么 if - 块 >>>> if(!variable) <<<<< 在 variable = 0 时执行?
【发布时间】:2020-11-07 18:07:34
【问题描述】:

当我运行这段代码时,if- 块中的代码会被执行。我的假设是 if ! something,它是 null 还是 未定义?谁能解释一下?

const num = 0;

if (!num) {
    console.log('Why on earth does this get printed');
}

【问题讨论】:

  • 0 是一个 falsy 值。这是唯一的假数。
  • 而且 !falsy 等于 true
  • 然后你的代码被执行了。
  • 谢谢!这个问题有什么问题???我真的没有理由对此投反对票……

标签: javascript if-statement types null undefined


【解决方案1】:

你的假设是错误的。当您像这样将一个值隐式转换为布尔值时,它会根据truthy and falsy rules 进行转换。虚假值为0""NaNnullundefined,当然还有false。 (另外,有趣的是,document.all 在浏览器上。)所有其他值都是 truthy。所以如果num0if (!num) 将是真的,因为你已经否定了一个假值(使它成为true)。

如果您只想检查nullundefined,您可以使用== undefinednum == null(注意:==,而不是===),这两个都适用:

if (num == null) {
    console.log("num is null or undefined");
}

== 的规则是,nullundefined 都是 == undefined(还有 == null),但没有别的。

或者,也许更清楚:

if (num === null || num === undefined)
    console.log("num is null or undefined");
}

【讨论】:

    【解决方案2】:
    • 当您使用 if 语句时,花括号中的代码仅在圆括号中的表达式返回 true 时才会执行。
    • 你的变量 num 被分配了 0。
    • 变量 num 将被转换为 false,因为它被分配了 0
    • 在 Javascript 中,感叹号 (“!”) 符号(称为“bang”)是逻辑“非”运算符。放在布尔值前面,它将反转该值,返回相反的值。
    • 正因为如此,你将在花括号内得到正确的结果
    • 这是您的代码执行的原因

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      相关资源
      最近更新 更多