在 if 语句中,undefined 等于 false

In if statement,undefined equals with false

我对下面的代码感到困惑:

if(undefined){
   //code will not be executed
}

if(!undefined){
   //code will be executed
}

这是否意味着 "undefined" 等于 false?

这里有the question相关,但是上面的情况没有一点出来。

表示undefined是一个伪值,伪值列表是:

""        // Empty string
null      // null
undefined // undefined, which you get when doing: var a;
false     // Boolean false
0         // Number 0
NaN       // Not A Number eg: "a" * 2

如果你否定一个虚假的价值,你会得到真实的:

!""        === true
!null      === true
!undefined === true
!0         === true
!NaN       === true

当你唠叨一个真值时,你会得到假值:

!"hello" === false
!1       === false

但是undefined不等于false:

undefined === false // false
undefined  == false // false

如果它只是为了好玩:

undefined == null // true

在javascript严格模式下,undefined不为假,但javascript尝试将对象或var转换为boolean值(这在javascript 真实值),这就是你得到 undefined 为假的原因。例如,null 也会发生这种情况。

你可以强制使用这个严格的不相等:

if(undefined!==false) console.log("Is not false"); 

请查看下面检查的虚假值:

""==false?
    Ans: true
null == false?
    Ans: false
undefined == false?
    Ans: false
0 == false?
    Ans: true
NaN == false?
    Ans: false
null == NaN?
    Ans: false

我们可以看到 null == falseundefined == falsenull == NaNNaN == false 不是 true 这意味着它们不相等。从上面的结果中,我们得到了 3 个假值组:

  1. 错误组
  2. Null 组和
  3. NaN 组

但负假值始终为真:

!""        === true
!null      === true
!undefined === true
!0         === true
!NaN       === true

例如: 检查 dataTitle 变量

true
if(dataTitle && (dataTitle != null))
{
    console.log('hi');
}

以上语句将检查假组和空组

检查 dataTitle 变量的 false

if(!dataTitle)
{
    console.log('hi');
}

//or 

if(dataTitle==null || dataTitle===false)
  console.log('hi');

在 javascript 中,undefinednull 是在全局范围内声明的空属性。 他们的价值不等于false;它们都具有原始值 undefined.

undefined == false // false

话虽如此,两者都会在程序化 true/false 评估中产生 false 值。在您的示例中,您使用了 logical NOT 运算符 (MDN):

Returns false if its single operand can be converted to true; otherwise, returns true

取反运算符首先将 undefined 求值为 false,然后取值为 true。你可以大致这样说明这个过程:

if (!(!!undefined)) {
    // code will be executed
}