null 与 undefined 的区别

undefined 表示一个变量已经声明,但没有被赋给任何值,包括 null

let foo
console.log(foo) // undefined

// 对象没有赋值的属性
let obj = {}
obj.name // undefined

调用函数时没有传递需要使用到的参数,没有明确的返回值等,都为 undefined

function foo(a) {
  console.log(a) // undefined
}

foo() // undefined

null 表示一个变量没有值。

let foo = null
console.log(foo) // null

如果您熟悉原型链,您可能知道原型链的最终值为 null

Object.getPrototypeOf(Object.prototype) // null

undefinednull 被认为是不同的类型。

undefined 是类型本身,而 null 是一个对象的特殊值。

console.log(typeof undefined) // 'undefined'
console.log(typeof null) // 'object'

由于它们是不同的类型,下面是相等和严格相等运算符在相互比较时的结果:

null == undefined // true
null === undefined // false

您可能不知道的是,在使用 JSON.stringify 方法时,JSON.stringify 将自动省略值为 undefined 的数据,但保留了 null:

JSON.stringify({
  name: 'O.O',
  address: null,
  age: undefined
})

// '{"name":"O.O","address":null}'

更多资料

undefined与null的区别

全部评论

相关推荐

2025-12-30 16:42
同济大学 C++
仁狂躁使者:哎呀,不用担心,我当时配环境配了两天,项目捋不清就问问导师能不能用ai,慢慢就清了,会好起来的
点赞 评论 收藏
分享
2025-12-11 14:24
门头沟学院 Java
牛客35720396...:不要用boss,全是骗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务