最主要来说,null是没有值,空的,但是undefined是缺少值,应该有值只是没定义。
记住这句话就完事了。
不同之处:
Number类型数值转换不同
console.log(Namber(null)); //0
console.log(Namber (undefined)); //NAN
typeof 运算输出值不同
null: null类型,代表“空”,代表一个空对象指针,使用typeof运算得到"object"。
undefined:undefined类型,当一个声明了一个变量未初始化时,得到的就是"undefined"
console.log(typeof null); // 'object'
console.log(typeof undefined); // 'undefined'
设置为null的变量或者对象会被内存收集器回收
相同点:
实际上,undefined值是派生自null值的,ECMAScript标准规定对二者进行相等性测试返回true。也就是说在js的隐式转换中,if判断都是false
console.log(null === undefined); // false
如何区分什么时候是null什么时候是undefined
何时是null,何时是undefined
null表示"没有对象",此处应该无值。例如:
1、作为函数的参数,表示该函数的参数不是对象
2、作为对象原型链的终点
undefined表示"缺少值",此处应该有值却未定义。例如:
1、声明的变量未赋值时等于undefined
2、调用函数未传递应有的参数时,对应参数等于undefined
3、对象的属性没有赋值时等于undefined
4、函数没有返回值时,默认返回undefined