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

本文深入探讨JavaScript中undefined与null的区别与联系,包括它们的类型、使用场景及类型转换规则,帮助读者理解这两个概念在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在“谈谈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
falsethrows 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值