首页 文章

关于null和undefined的类型转换

提问于
浏览
0

众所周知,null和undefined是假值 . 但是为什么第一段代码工作而第二部分不工作呢?

// #1
if (!undefined) {   // or (!null)
  console.log("hi"); // => hi
}
enter code here

// #2
if (undefined == false) {  // or (null == false)
  console.log("hi"); => never gets executed
}

是否有特定原因或者仅仅是语言规范?其他虚假值,如0,“”,false(NaN除外)工作,我猜他们正在转换为false .

3 回答

  • 0

    因为"falsey"与等于 false 不同,这就是为什么需要发明这个术语的原因 .

  • 0

    根据定义, undefined 仅等于 null ,但不是 false

    undefined == null // true
     undefined == false // false
    

    是的,这不是出于某种特定原因,只是为了让人迷惑:

    [] == false // true
    

    所以你可以从这里学到的,就是你应该总是使用 ===

  • 2

    首先, undefinednull 是两个不同的原始值 .

    undefined 表示变量已创建但未分配任何 value 因此它充当 falsy 值,而 null 表示不存在的参考,因此它也是 falsy ,现在在您的情况下,

    if(undefined==false){
         //the code in here will never be executed
    }
    
    • 因为 undefined 没有值而 false does.so,

    undefined==false
    //is false as false(with a value) can't be 
    //equal to undefined which has no value
    

相关问题