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
本文详细介绍了JavaScript中null和undefined的区别,包括它们的定义、类型检查以及常见使用场景。null表示一个空对象,而undefined表示值未定义。在验证时,建议使用严格相等运算符(===)。文章列举了导致undefined的6种情况,并提供了多个示例来帮助理解。了解这些概念对于JavaScript编程至关重要。

9160

被折叠的 条评论
为什么被折叠?



