整理了网上资料【※注1】,结合起来理解比较好:
一、 相同点
·if 判断语句中,两者都会被转换为false
·二者值判断(==)结果相等
null == undefined//true
二、不同点
·Number转换的值不同,
Number(null) 输出为 0,
Number(undefined)输出为 NaN。
·1、null
null的类型是Object,表示"没有对象",即该处不应该有值。
典型用法是:
(1) 作为函数的参数,表示该函数的参数不是对象。
(2) 作为对象原型链的终点【※注2】
Object.getPrototypeOf(Object.prototype)
(3) 清空对象直接赋值为null,而不是用delete
(4) 定义一个值为null是合理的,但定义为undefined不合理(var name = null)
·2、undefined
undefined的类型为Undefined,表示"缺少值",就是此处应该有一个值,但是还没有定义。
典型用法是:
(1)变量被声明了,但没有赋值时,就等于undefined。
var i;
i // undefined
(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。
function f(x){console.log(x)}
f() // undefined
(3)对象没有赋值的属性,该属性的值为undefined。
var o = new Object();
o.p // undefined
(4)函数没有返回值时,默认返回undefined。
var x = f();
x // undefined
二者类型区别:
null == undefined//true
null === undefined //false
typeof null == typeof undefined//false
typeof undefined === 'undefined'//true
typeof null === 'object'//true
【※注1】:
https://blog.csdn.net/qq_38921817/article/details/77145759
https://www.mk2048.com/blog/blog_hjbh220h10bb.html
https://blog.csdn.net/wuyitong116/article/details/90488044
https://blog.csdn.net/weixin_39713762/article/details/93807832
【※注2】:关于 原型链 的定义,参见:
js(原型对象与原型链)
https://www.cnblogs.com/lyx1014/p/11040462.html
JS高级---原型链(一看就懂,但18岁以下请绕道)
https://blog.csdn.net/xiaotao_css/article/details/72782416