无标题文章

2017-02-21  本文已影响2人  凸小布

null和undefined到底有什么区别?

null 表示一个对象是“没有值”的值,也就是值为“空”;
undefined 表示一个变量声明了没有初始化(赋值);

var a;
console.log(typeof a);//undefined

undefined不是一个有效的JSON,而null是;

undefined的类型(typeof)是undefined;
null的类型(typeof)是object;

console.log(null instanceof Object); //false
console.log(typeof null); //object
console.log(typeof undefined); //undefined

Javascript将未赋值的变量默认值设为undefined;
Javascript从来不会将变量设为null。它是用来让程序员表明某个用var声明的变量时没有值的。


typeof undefined 和 typeof null

typeof undefined
//"undefined"
undefined :是一个表示"无"的原始值或者说表示"缺少值",就是此处应该有一个值,但是还没有定义。当尝试读取时会返回 undefined;
例如变量被声明了,但没有赋值时,就等于undefined

typeof null
//"object"
null : 是一个对象(空对象, 没有任何属性和方法);
例如作为函数的参数,表示该函数的参数不是对象;

注意:
在验证null时,一定要使用 === ,因为 == 无法分别 null 和 undefined

 console.log(null == undefined);   //true
 console.log(null === undefined);  //false

什么时候我们的变量值为null什么时候为undefined?

答案:变量的值永远都不可能为null,除非我们手动的赋值为null

为什么需要设置为null?

告诉系统这个变量不再使用,可以把占用的空间回收了


参考阅读
undefined与null的区别
前端开发面试题

上一篇 下一篇

猜你喜欢

热点阅读