根据JavaScript 中 null 和 undefined 有什么区别? https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript, null
and undefined
是 Javascript 中的两个不同的对象(具有不同的类型)。但是当我尝试这段代码时
var a=null;
var b;
alert(a==null); // expecting true
alert(a==undefined); // expecting false
alert(b==null); // expecting false
alert(b==undefined); // expecting true
上述代码的输出是:
true
true
true
true
Now as ==
只匹配值,我认为两者undefined
and null
必须具有相同的值。所以我尝试:
alert(null)
-> 给出null
alert(undefined)
-> 给出undefined
我不明白这怎么可能。
Here is the demo http://jsfiddle.net/A89Qj/1/.
Edit
我明白那个===
会给出预期的结果,因为undefined
and null
有不同的类型,但是在 Javascript 中类型转换如何工作==
?我们可以像 Java 中那样进行显式类型转换吗?我想应用手动类型转换undefined
and null
.
您需要使用身份算子===,不是等于运算符== https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-us。通过此更改,您的代码按预期工作 http://jsfiddle.net/A89Qj/2/:
alert(a===null); // true
alert(a===undefined); // false
alert(b===null); // false
alert(b===undefined); // true
在这种情况下,相等运算符失败的原因是它尝试进行类型转换。undefined
属于类型undefined
, and null
属于类型object
;在尝试比较两者时,Javascript 将两者都转换为false
,这就是为什么它最终认为它们相等。另一方面,恒等运算符不进行类型转换,并且要求类型相等才能得出相等性。
Edit 感谢@user1600680 指出,以上内容并不完全正确; ECMAScript 规范将 null 到 undefined 定义为特殊情况,并且相等。没有中间转换false
.
A simpler example of type conversion is number-to-string:
console.log(5 == "5"); // true
console.log(5 === "5"); // false
上面的答案很好地引用了 Douglas Crockford 的一句话Javascript:好的部分:
当操作数具有相同类型时,[“==”运算符会做正确的事情,但如果它们具有不同类型,它们会尝试强制这些值。他们所做的事情的规则是复杂且难以记忆的。
如果你不相信规则复杂且难以记忆, a 快速浏览一下这些规则 http://jibbering.com/faq/notes/type-conversion/会让你打消这个念头。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)