Skip to content

null 和 undefined 的区别

  • undefined 代表的含义是未定义

    • 变量声明但没有定义时,是 undefined

    • 一个函数没有明确的返回值, 接收这个函数调用的返回值, 是 undefined

    • 访问对象中不存在的属性,是 undefined

    • 函数参数未传递,是 undefined

    • 数组中出现空位,是 undefined

  • null 代表的含义是空指针

    • 不明确初始值时, 赋值为 null 用来占位

    • 释放对象/常量时, 赋值为 null

javascript
typeof null; // "object"
typeof undefined; // "undefined"

const undefined = 1
undefined // 1
let null = 123 // Error, SyntaxError: Unexpected token 'null'

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

JSON.stringify({ foo: undefined, bar: null }) // {"bar":null},值为 undefined 的属性会被忽略。
JSON.stringify([null, undefined, null]) // [null,null,null],undefined 会变为 bull