比较null-JavaScript中的!== vs!= [英] Comparing to null - !== vs != in JavaScript

查看:48
本文介绍了比较null-JavaScript中的!== vs!=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我在使用node.js应用程序时在Sublime编辑器上安装了Linter。它捕获到的一件事是,我应该始终使用!==将对象与null进行比较(我通常使用!=)。

Ok, so I installed Linter on my Sublime editor while working on my node.js app. One of the things that it caught said that I should always use !== to compare an object to null (I usually use != ).

所以我更改了它。 ..但后来我发现!==无效。

So I changed it...but then I noticed that the !== wasn't working.

我有这种情况:

var x = null;
if (x !== null)
    console.log('x is not equal to null');

当我使用!==时,控制台显然会打印该行。当我将其切换回!=时,它的行为正常。

When I use the !== the console printed that line even though it was obviously not true. When I switched it back to != it behaved normally.

所以我的问题是,为什么lint告诉我使用!==如果它没有执行我的操作希望它...

So my question is, why is linter telling me to use !== if it doesn't do what I want it to...

我知道我丢失了一些东西。

I know I am missing something.

更新
好​​的,所以它可能比我最初想象的要复杂一些。在我的真实代码中,我对node.js GLOBAL对象使用!==。

UPDATE Ok, so it may be a bit more complicated than I originally thought. In my real code I was using !== with the node.js GLOBAL object.

console.log('Global User: ' + GLOBAL.User);

if (GLOBAL.User != null)
{
    console.log('User is not null');
}

即使GLOBAL.User为空,控制台行也会打印出来。

The console line prints even when GLOBAL.User is null...

也许这个对象很特殊吗?

Perhaps this object is special?

更新2

好,所以在阅读完注释并查看了我的代码后,我知道了!=如果对象未定义而不是null,则=可能会出现问题(请参见此帖子:为什么对象为null以及null和undefined之间有什么区别?)。

Ok, so after reading through the comments and looking at my code, I have learned that !== can have issues if the object is undefined rather than null (see this post: Why is null an object and what's the difference between null and undefined?).

在我的情况下,根据调用此方法的时间,全局变量可能是未定义的,空的或充满数据的。我将回过头来更新我的代码,以使它永远不会被定义,然后!==将始终如一地工作。

So in my case, my global variable could be, depending on when this method is called, undefined, null, or full of data. I am going to go back and update my code so that it is never undefined and then !== will work consistently.

感谢您的帮助!

谢谢,
David

Thanks, David

推荐答案

您的 global.User 未定义,而不是 null 。使用 == 时,它们的评估结果相等,但是使用 === 时,要比较的项目必须相同类型。 未定义具有类型未定义 null 具有类型对象

Your global.User is undefined, not null. When using == they evaluate to equal, but with === the items you are comparing need to be the same type. undefined has the type undefined and null has the type object.

未定义 null 非常相似,但是它们通常表示两个截然不同的东西。通常,未定义是没有赋值的结果,而 null 有一个值,并且该值明确设置为无。

undefined and null are very similar, but they generally mean two very different things. Usually undefined is the result when something has had no value assigned to it, whereas null has a value, and the value is explicitly set to "nothing".

这篇关于比较null-JavaScript中的!== vs!=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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