相同
在 if 语句中 null 和 undefined 都会转为false两者用相等运算符比较也是相等
undefined 和 null 都是基本数据类型,这两个基本数据类型分别都只有一个值,就是 undefined 和 null。
不同
undefined:
- 已声明但未被初始化的变量默认赋值undefined
- 未被声明的变量使用typeof操作符检测数据类型时返回undefined
- 当函数没有明确指定返回值时,默认返回undefined
function fun(){ console.log(333); } console.log(fun());
- void()返回undefined
console.log(void(0)===window.undefined)//true console.log(void(0)===undefined);//true
null:
null 代表的含义是空对象。也作为对象原型链的终点
null 主要用于赋值给一些可能会返回对象的变量,作为初始化。