简体   繁体   English

我应该使用!==还是==! 在检查不相等时?

[英]Should I use !== or ==! when checking for not equal?

Should I use !== or ==! 我应该使用!==还是==! ? Both work, but what is the standard? 两者都可以,但是标准是什么?

I enter "else" for both cases: 在两种情况下,我输入“ else”:

var x;
if (x !== undefined)
{
    alert("if..");
}
else
{
    alert('else..') // <--- here
}


var y;
if (y ==! undefined)
{
    alert("if..");
}
else
{
    alert('else..') // <--- here
}

==! is not a comparison operator in Javascript. 不是Javascript中的比较运算符。 When you write foo ==! bar 当你写foo ==! bar foo ==! bar , you are actually writing foo == !bar , using the unary ! foo ==! bar ,实际上是使用一元代码编写foo == !bar ! negation operator and the binary == comparison operator. 否定运算符和二进制==比较运算符。 This probably does not do what you want it to: 这可能不满足您的要求:

> 'b' ==! 'a'
false
> 'b' !== 'a'
true

This happens to "work" in the particular situation you describe because !undefined evaluates to true , and y == true for undefined y is false , thus putting you on the else branch. 在您描述的特定情况下,这会发生“工作”,因为!undefined值为true ,而y == true的未定义yfalse ,因此您进入了else分支。

if (x !== undefined)

checks if x is not undefined, while 检查x是否未定义,而

if (y ==! undefined)

negates undefiend (which returns !undefined == true ) and then checks it for equality with y undefiend (返回!undefined == true ),然后与y进行相等性检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM