一. 相同点
- 同为5种基本数据类型之列(
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 - JSON序列化:JSON规范中被强化,这个标准中不存在
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 不同:
typeof null === "object"更可能是一个设计失误,所以在 harmony 中有提议将这个返回值修正为null,但是该提议因为会造成大量旧 Javascript 脚本出现问题而被否决了。typeof null // "object" typeof undefined // "undefined" null instanceof Object // false - 设置为
null的变量或者对象会被内存收集器回收,undefined不会。
三. 为什么JS 中会同时存在 undefined 和 null ?
JS 中同时存在 undefined 和 null 是合理的。
首先在 Java 中不存在 undefined 是很合理的:Java 是一个静态类型语言,对于 Java 来说不可能存在一个“不存在”的成员(不存在的话直接就编译失败了),所以只用 null 来表示语义上的空值。而 JavaScript 是一门动态类型语言,成员除了表示存在的空值外,还有可能根本就不存在(因为存不存在只在运行期才知道),所以这就要一个值来表示对某成员的 getter 是取不到值的。
(文章纯属个人备忘记录用途,部分引用来自网上加上个人理解整理。欢迎转载,请注明出处。如对你有帮助,请随意打赏。)