面试官🤔:JS 中的 null 有啥用…

68 阅读1分钟

Screenshot 2024-08-14 at 23.31.49.png

含义

The null value represents the intentional absence of any object value

null 用来表示一个有意不存在的值

使用场景:

// 初始化的变量没有值
let person = null;

// 函数的返回值是一个空值
function findPersonById(id) {
    const person = /* 逻辑来查找人 */;
    if (!person) {
        return null;
    }
    return person;
}

// 对象的某个属性不存在
const user = {
    name: 'John',
    age: null // 表示年龄未知或未设置
};

// 标记一个已经删除或者无效的项
const todos = [null, { id: 2, text: 'Buy milk' }, { id: 3, text: 'Read book' }];

其他

它是原始类型之一
  • string
  • number
  • bigint
  • boolean
  • undefined
  • symbol
  • null
typeof
typeof null // object  这是历史原因,得到的结果不是 null
typeof undefined // undefined
比较
null == undefined // true
null === undefined // false
可选链

如果 ?. 作用于 nullundefined 时,返回 undefined 而不会报错

const a = { k: null }
a.k?.v // undefined
序列化
// 属性值为 null,可以被序列化
const obj = { key: null };
console.log(JSON.stringify(obj)); // {"key":null}