【发布时间】:2023-03-18 00:30:01
【问题描述】:
根据What is the difference between null and undefined in JavaScript?,null 和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
现在== 只匹配值,我认为undefined 和null 必须具有相同的值。所以我尝试了:
alert(null) -> 给null
alert(undefined) -> 给undefined
我不明白这怎么可能。
这里是the demo。
编辑
我知道=== 会给出预期的结果,因为undefined 和null 具有不同的类型,但是在== 的情况下,JavaScript 中的类型转换如何工作?我们可以像在 Java 中那样进行显式类型转换吗?我想对undefined 和null 应用手动类型转换。
【问题讨论】:
-
你想用什么方式转换它们?两者都为空?
-
你要么未定义为对象(空类型)或
null到undefined -
myVal = myVal == null ? null : myVal;应该可以解决问题。现在它绝对不是未定义的。 -
@JonHanna 我期待一些更像
(typeof(undefined))(null)的东西,上面更像是基于null==undefined的谓词的 if 和 else -
就是这样。不,这不好。
标签: javascript