null
, undefined
, number
, string
, boolean
)。undefined
和null
在if语句中,都会被自动转为false
,相等运算符甚至直接报告二者相等。if (!undefined) console.log('undefined is false');
// undefined is false
if (!null) console.log('null is false');
// null is false
undefined == null
// true复制代码
null
表示一个值被定义了,定义为“空值”;undefined
表示根本不存在定义。因此设置一个值为 null
是合理的,如objA.valueA = null;
但设置一个值为 undefined
是不合理的。null
转为数值时为0;undefined
转为数值时为NaN
。可是 parseInt
和parseFloat
不这么认为:parseInt(null)
和 parseFloat(undefined)
返回都是 NaN
。Number(null)
// 0
Number(undefined)
// NaN
parseInt(null)
// NaN
parseFloat(undefined)
// NaN
null === undefined
// false
复制代码
undefined
这个类型,但存在表示空值的 null
。在一些使用普遍的库(好比jQuery)中的深度拷贝函数会忽略 undefined
而不会忽略 null
,http接口的报文参数也是如此。var json = {a: 1, b: undefined, c: null}
JSON.stringify(json)
// "{"a":1,"c":null}"
JSON.parse(JSON.stringify(json))
// {a: 1, c: null}复制代码
typeof null === "object"
更多是一个设计失误,因此在 harmony 中有提议将这个返回值修正为 null
,可是该提议由于会形成大量旧 Javascript 脚本出现问题而被否决了。typeof null
// "object"
typeof undefined
// "undefined"
null instanceof Object
// false复制代码
null
的变量或者对象会被内存收集器回收,undefined
不会。JS 中同时存在 undefined
和 null
是合理的。javascript
首先在 Java 中不存在 undefined 是很合理的:Java 是一个静态类型语言,对于 Java 来讲不可能存在一个“不存在”的成员(不存在的话直接就编译失败了),因此只用 null 来表示语义上的空值。而 JavaScript 是一门动态类型语言,成员除了表示存在的空值外,还有可能根本就不存在(由于存不存在只在运行期才知道),因此这就要一个值来表示对某成员的 getter 是取不到值的。php
(文章纯属我的备忘记录用途,部分引用来自网上加上我的理解整理。欢迎转载,请注明出处。如对你有帮助,请随意打赏。)java