众所周知,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。
答案 0 :(得分:2)
因为“虚假”与等于false
等于 不同,这就是为什么需要发明该术语的原因。
答案 1 :(得分:0)
undefined
仅等于null
,但根据定义不等于false
:
undefined == null // true
undefined == false // false
是的,那并不是真的出于特定原因,只是为了使人们感到困惑:
[] == false // true
因此,您可以从此中学到的就是应该始终使用===
答案 2 :(得分:0)
首先,未定义和空是两个不同的原始值。
未定义表示已创建变量,但未为其分配任何值 因此它是一个虚假值,而 null 表示不存在的引用,因此它也是虚假, 现在,就您而言,
if(undefined==false){
//the code in here will never be executed
}
->因为未定义没有价值,而 false 却没有价值。
undefined==false
//is false as false(with a value) can't be
//equal to undefined which has no value