JavaScript:`if(!x)`和`if(x == null)`有什么区别? [英] JavaScript: What is the difference between `if (!x)` and `if (x == null)`?

查看:897
本文介绍了JavaScript:`if(!x)`和`if(x == null)`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

!x 将为每个falsy值返回 true (空字符串, 0 null false undefined NaN )而 x == null 只返回 true 如果 x null 编辑:或显然未定义(见下文))。



尝试 x = 0 ,有区别。



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



此外,如果您将值与 == ,JavaScript会 类型转换 ,这会导致意外行为(如 undefined == null )。最好总是使用严格比较 === (值和类型必须相同)并且只有在你真正知道自己在做什么时才使用类型转换。 / p>

需要阅读的内容:








更新:



有关<$ c $的非严格比较的详细信息c> null undefined (或一般的比较),值得一看 规范 。比较算法在那里定义(比较是 x == y ):



  1. 如果Type( x )与Type( y )相同,那么

    (...)

  2. 如果 x null y 未定义,则返回即可。

  3. 如果 x 未定义 y null ,则返回 true

  4. (...)

(.. 。)



What is the difference between if (!x) and if (x == null); that is, when can their results be different?

解决方案

!x will return true for every "falsy" value (empty string, 0, null, false, undefined, NaN) whereas x == null will only return true if x is null (edit: or apparently undefined (see below)).

Try with x = 0, there is a difference.

You can say that the NOT operator ! converts a value into its opposite boolean equivalent. This is different than actually comparing two values.

In addition, if you compare values with ==, JavaScript does type conversion which can lead to unexpected behavior (like undefined == null). It is better to always use strict comparison === (value and type must be the same) and make use of type conversion only if you really know what you are doing.

Something to read:


Update:

For more information about the non-strict comparison of null and undefined (or the comparison in general), it is worth having a look at the specification. The comparison algorithm is defined there (the comparison is 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)`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆