=== 和 == 如何以不同方式处理 null 比较?
我有一个简单的 json 解析对象,有时定义了变量 tt,有时则没有。
由于某种原因,jsonobject.tt == null
根据是否定义了 tt
正确返回 1
或 0
。无论如何,jasonobject.tt === null
只是返回0
。我认为 ===
是用来避免问题的东西。
这是怎么回事?
I have a simple json parsed object that sometimes has a variable tt
defined and sometimes doesn't.
For some reason jsonobject.tt == null
returns correctly 1
or 0
based on whether tt
is defined. jasonobject.tt === null
just returns 0
regardless. I thought ===
was the thing to use to avoid issues.
What's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
===
是严格相等运算符,它比较类型和值。值null
是 Null 类型,只有一个值 -null
。Undefined 是未定义类型,它也只有一个值 - 'undefined'。
使用严格相等运算符时, null !== undefined 因为它们是不同的类型(请参阅严格相等比较算法的步骤 1,ECMA-262 § 11.9.6)。
==
是相等运算符。使用==
的比较使用抽象相等比较算法 (ECMA-262 § 11.9.3),其中包括:因此,
null == undefined
根据定义返回 true。严格来说,测试某个属性是否存在(无论其值是多少),应该使用 hasOwnProperty:但实际上,与严格测试 undefined 没有太大区别:
因为属性是否存在且值为未定义或者根本没有定义通常是等价的。使用
===
还意味着,如果 tt 存在但已被赋值为null
,则上述代码将返回 false。===
is the strict equality operator, it compares type as well as value. The valuenull
is the Null Type that has exactly one value -null
.Undefined is the Undefined Type, which also has only one value - 'undefined'.
When using the strict equality operator, null !== undefined because they are different types (see step 1 of the Strict Equality Comparison Algorithm, ECMA-262 § 11.9.6).
==
is the equality operator. Comparisons using==
use the Abstract Equality Comparison Algorithm (ECMA-262 § 11.9.3), which includes:So
null == undefined
returns true by definition. Strictly, testing for the presence of a property (regardless of its value), should use hasOwnProperty:however in practice there isn't much difference to a strict test for undefined:
because whether the property exists and has a value of undefined or hasn't been defined at all is usually equivalent. Using
===
also means that the above will return false if tt exists but has been assigned a value ofnull
.首先比较返回
true
或false
其次你想要
jsonobject.tt === undefined
如果一个值不存在,那么它是未定义的。
其他检测方法有
!jsonobject.hasOwnProperty("tt");
或
!("tt" in jsonobject)
作为
==
是一个完全奇怪的运算符,null == undefined
。因此,如果该属性不存在,jsonobject.tt == null
将返回 trueFirstly a comparison returns
true
orfalse
Secondly you want
jsonobject.tt === undefined
If a value does not exist it is undefined.
Other detection methods are
!jsonobject.hasOwnProperty("tt");
or
!("tt" in jsonobject)
As a side effect of
==
being a totally weird operator,null == undefined
. Thusjsonobject.tt == null
will return true if the property is not there如果变量尚未定义,则其值为
未定义
。然而
If a variable hasn't been defined it has a value of
undefined
.whereas