null和undefined区别
1. null和undefined的区别:
- null 是一个表示"无"的 对象的初始值,空对象的引用 ; 转为数值时为 0
null 用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象- undefined 是一个表示"无"的原始值的初始值 ; 未定义 ; 转为数值时为 NaN
当声明的变量还未被初始化时,变量的默认值为 undefined
2. undefined
undefined 表示 “缺少值”,就是此处应该有一个值,但是还没有定义。
典型使用场景是:
1.变量被声明了,但没有赋值时,就等于 undefined
2.调用函数时,应该提供的实参数没有提供获取形参,该参数等于 undefined
3.对象没有赋值的属性,该属性的值为 undefined
4.函数没有返回值时,默认返回 undefined
5.void()
3. null
null 表示“没有对象”,即该处不应该有值。
典型使用场景是:
1.作为函数的参数,表示该函数的参数不是对象
2.作为对象原型链的终点
4. 举例
console.log(typeof undefined). //undefined
console.log(Boolean(undefined)). //false
console.log(String(undefined)). //undefined
console.log(Number(undefined)). //NaN
console.log(typeof null). //object
var arr = [] //定义空数组
var obj = {}//定义空对象
console.log(Boolean(null)). //false
console.log(String(null)). //null
console.log(Number(null)). //0
console.log(undefined == null) //true
console.log(undefined === null) //false
参考阮一峰:http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?