谈谈JavaScript undefined和null的区别和联系、常用使用场景及两者相关的类型转换

在“谈谈JavaScript的算数运算、二进制浮点数舍入误差及比较、类型转换和变量声明提前问题”一文中提到了undefined、null类型转换。由于undefined和null都表示值的空缺,并且undefined==null为true,但两者又不尽相同,本文就谈谈详细谈谈两者的区别和联系、使用场景及两者相关的类型转换。

1、两者区别和联系

undefined和null都表示值空缺的意思,undefined 从null 派生而来,因此undefined==null 返回true,两者往往可以互换。

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

undefined 是基本数据类型,声明了变量但未对其初始化时赋予该变量的值,是全局对象(window)的一个特殊属性。
null 是引用数据类型,用于表示尚未存在的对象,所以:

typeof undefined;	->"undefined"
typeof null;		->"object"
console.log(undefined === null); 	->false

2、两者常用使用场景

null使用场景:

  • 作为函数的参数,表示该函数的参数是正常或意料之中的值的空缺。
  • 作为对象原型链的终点。
Object.prototype.__proto__;	->null
  • 解除对象引用,便于垃圾回收
var student = {no:1,name:"name-1"};
...
student = null;

undefined使用场景:

  • 全局作用域判断变量是否存在,或者声明了,但是没有赋值
var a;
var c = 1;
console.log(typeof a === "undefined")	->true
console.log(typeof b === "undefined")	->true
console.log(typeof c === "undefined")	->true
  • 函数调用,应该提供的参数没有提供,该参数等于undefined。
function sayHello(name, msg) {
	console.log("name: ", name);	->name: 老马
	console.log(typeof msg === "undefined");	->true
}
sayHello("老马");
  • 对象没有赋值的属性,该属性的值为undefined。
var person = {name: "老马"};
console.log(typeof person.age === "undefined");
  • 函数没有返回值时,默认返回undefined。
console.log(sayHello("老马") === undefined);

3、undefined和null相关的类型转换

字符串 数字 布尔值 对象
undefined
null
“undefined”
“null”
NaN
0
false throws TypeError
var a = null, b;
var c = 100, d = "string ";
console.log(a+c);		->100
console.log(b+c);		->NaN
console.log(d+a);		->string null
console.log(d+b);		->string undefined

猜你喜欢

转载自blog.csdn.net/chuangxin/article/details/84929548
今日推荐