null 和 undefined 的区别
区别
null
表示一个对象被定义了,值为“空值”
undefined
表示不存在这个值
typeof undefined //"undefined"在这里插入代码片
undefined
: 是一个表示 “无” 的原始值或者说表示 “缺少值” ,就是此处应该有一个值,但还 没有定义。当尝试读取时会返回 undefined
;
例如变量被声明了,但没有赋值时,就等于 undefined
null
: 是一个对象(空对象, 没有任何属性和方法);
typeof null //"object"
例如作为函数的参数,表示该函数的参数不是对象;
注意:
在验证 null
时,一定要使用===
,因为==
无法分别null
和 undefined
undefined
表示"缺少值",就是此处应该有一个值,但是还没有定义。
典型用法是:
- 变量被声明了,但没有赋值时,就等于
undefined
- 调用函数时,应该提供的参数没有提供,该参数等
undefined
- 对象没有赋值的属性,该属性的值为
undefined
- 函数没有返回值时,默认返回
undefined
null
表示"没有对象",即该处不应该有值。
典型用法是:
- 作为函数的参数,表示该函数的参数不是对象
- 作为对象原型链的终点
JavaScript
中什么情况下会返回 undefined
值?
1、访问声明,但是没有初始化的变量
var aaa
console.log(aaa) // undefined
2、访问不存在的属性
var aaa = {}
console.log(aaa.c)
3、访问函数的参数没有被显式的传递值
(function (b) {
console.log(b) // undefined
})()
4、访问任何被设置为 undefined
值的变量
var aaa = undefined;console.log(aaa) // undefined
5、没有定义 return
的函数隐式返回
function aaa(){}console.log(aaa()) // undefined
6、函数 return
没有显式的返回任何内容
function aaa(){
return
}
console.log(aaa()) // undefined