与 JavaScript 中的 null - !== vs != 进行比较

2022-01-25 00:00:00 compare javascript

好的,所以我在处理我的 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.

所以我的问题是,为什么 linter 告诉我使用 !== 如果它没有做我想要的...

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

我知道我错过了什么.

更新好的,所以它可能比我最初想象的要复杂一些.在我的真实代码中,我使用 !== 和 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...

也许这个对象很特别?

更新 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.

感谢您的帮助!

谢谢,大卫

推荐答案

你的 global.Userundefined,而不是 null.使用 == 时,它们的计算结果相等,但使用 === 时,您要比较的项目需要是相同的类型.undefined 的类型为 undefinednull 的类型为 object.

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.

undefinednull 非常相似,但它们通常意味着两个非常不同的东西.通常 undefined 是没有赋值的结果,而 null 有一个值,并且该值被显式设置为nothing".

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".

相关文章