JavaScript中 null和undefind有什么异同?

相同点:

1.都会转成falsejavascript

if(!undefined){
	console.log('undefined')
}
if(!null){
	console.log('null')
}
//输出 undefined null

2.并且使用相等来判断,是相等的html

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

3.它们都是数据类型,并且它们都只有一个值。java

不一样点:

感谢阮一峰老师的解答:http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html函数

1.null是一个表示"无"的对象,转为数值时为0;undefined是一个表示"无"的原始值,转为数值时为NaN。spa

Number(null); //0
 
5+null; //5

Number(undefined);// NaN

5 + undefined;// NaN

 

使用场合:

null的使用场合:

  1. 给对象赋值的时候使用。
  2. 做为函数的参数,表示该函数的参数不是对象。
  3. 做为对象原型链的终点。
Object.getPrototypeOf(Object.prototype)// null

undefined的使用场合:

  1. 变量被声明了,但没有赋值时,就等于undefined。prototype

  2. 调用函数时,应该提供的参数没有提供,该参数等于undefined。
  3. 对象没有赋值的属性,该属性的值为undefined。
  4. 函数没有返回值时,默认返回undefined。
相关文章
相关标签/搜索