1、从定义区别:
null:一个值被定义了,定义为“空值”;
undefined:根本不存在定义
所以设置一个值为 null 是合理的,例如 let a = null;而不是用 let a = undefined;
2、从判断是否相等区别:在javaScript中,null和undefined相等,却不全等
console.log(Boolean(null))//-->false
console.log(Boolean(undefined))//-->false
console.log('相等',null==undefined)//-->true
console.log(typeof null)//-->object
console.log(typeof undefined)//-->undefined
console.log('全等',null===undefined)//-->false
3、从用法上区别:
null
1)作为函数的参数,表示该函数的参数不是对象
2)作为对象原型链的终点
3) Number(null) --> 0
4) String(null) --> 'null'
5) Object(null) --> {}
6) 5 + null --> 5
7) JSON.stringify(null) --> 'null'
8)JSON.parse(null) --> null
undefined
1)变量被声明了,但没有赋值时,就等于undefined
2)调用函数时,应该提供的参数没有提供,该参数等于undefined
3)对象没有赋值的属性,该属性的值为undefined
4)函数没有返回值时,默认返回undefined
5) Number(undefined)--> NaN
6) String(undefined) --> 'undefined'
7) Object(undefined) --> {}
8) 5 + undefined --> NaN
9) JSON.stringify(undefined) --> undefined
10) JSON.parse(undefined) --> 报错,Uncaught SyntaxError: "undefined" is not valid JSON
补充:
null作为对象原型链的终点:
console.log(Object.getPrototypeOf(Object.prototype))//-->null