gpt4 book ai didi

JavaScript: `if (!x)` 和 `if (x == null)` 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-03 02:57:34 28 4
gpt4 key购买 nike

if (!x)if (x == null) 之间有什么区别?也就是说,他们的结果什么时候可以不同?

最佳答案

!x 将为每个“falsy”值返回 true(空字符串、0nullfalseundefinedNaN) 而 x == null 只会返回 true if x is null (编辑:或明显未定义(见下文)) .

尝试使用x = 0,有区别。

您可以说 NOT 运算符! 将一个值转换为其相反的 bool 值。这与实际比较两个值不同。

此外,如果您将值与 == 进行比较,JavaScript 会 type conversion这可能会导致意外行为(例如 undefined == null)。最好始终使用严格比较 === (值和类型必须相同),并且仅在您真正知道自己在做什么时才使用类型转换。

要读的东西:

<小时/>

更新:

有关 nullundefined 的非严格比较(或一般比较)的更多信息,值得一看 specification 。比较算法在那里定义(比较是x == y):

  1. If Type(x) is the same as Type(y), then
    (...)
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. (...)

(...)

关于JavaScript: `if (!x)` 和 `if (x == null)` 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5791158/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com