在 JS 中,我们需要经常检查对象的某些属性是否存在,然后才能再处理它,不然会报错。早期我们可能会这么干:

const toto = { a: { b: { c: 5 } } }

if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist

如果对象嵌套很深,我们这写法就难以阅读,这时可以使用 ? 来简化:

if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist

// 如果键不存在,返回 `undefined`。
const test = toto.a?.b?.c?.d // undefined
const test = toto.a?.b?.c // 5