js 中null 和 undefined 区别

108 阅读1分钟

一、相同点:

1、都是原始类型的值,且保存在栈中变量本地

2、进行条件判断时,两者都是false:

console.log(undefined == null);//true  ECMAScript认为undefined是null派生出来的,所以定义他们值是相同的

二、不同点

1、null是js的关键字,表示空值;undefined不是js的关键字,它是一个全局变量

2、null是Object的一个特殊值,如果一个Object为null,表示这个对象不是有效对象,null是一个不存在的对象的占位符;undefined是Globel的一个属性

3、类型不一样:

 typeof(null) // object
 typeof(undefined) //undefined
 console.log(typeof(null) === 'object')//true
 console.log(typeof(undefied) === 'undefined')//true

4、转换的值不一样:

console.log(Number(undefined));//NaN
console.log(Number(11+ undefined));//NaN

console.log(Number(null));//0
console.log(Number(11+ null));//11

三、null何时使用

当需要释放一个对象的时候可以将该对象赋值为null,进而来释放对象

var a = {
  a:1,
  b:2
};
a = null;

null、undefined是怎么产生的

1、产生null方式一:当访问一个不存的DOM节点时

console.log(document.getElementById(“#aaaaaaa”));//null

2、产生null方式二:Object的原型链终点:

console.log(Object.prototype.__proto__);//null

1、产生undefined方式一:声明了变量但未赋值:

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

2、产生undefined方式二:对象的属性没有赋值的情况下:

var obj = {a:1}; 
console.log(obj.age)//undefined

3、产生undefined方式三: 函数调用的时候,函数的参数没有提供的情况下:

function add(num){ 
 console.log(num)
}; 
add();//undefined

4、产生undefined方式四:当函数没有返回值的情况下:

var a = function(){};
console.log(a())//undefined