安全地"一层一层往下找"。中间哪一层没有,直接返回 undefined,不会报错。
| 以前 · 层层 && 判断 | 现在 · ?. 直接往下找 |
|---|---|
let config = { db: { host: "localhost" } };
let host = config && config.db && config.db.host;
console.log(host);
// localhost
|
let config = { db: { host: "localhost" } };
let host = config?.db?.host;
console.log(host);
// localhost
console.log(config?.x?.y);
// undefined(不报错)
|
以前每层都要写 && 判断"有没有",一长串;现在 ?. 一放,中间没有就直接返回 undefined,不报错。
"判断之后再赋值"压缩成一个运算符:||=、&&=、??=。
| 以前 · 先判断再赋值 | 现在 · 一步到位 |
|---|---|
let a = false; a = a || true; // 左边是假 → 赋值 let b = null; b = b ?? "默认值"; // 左边是 null → 赋值 |
let a = false; a ||= true; // 左边是假 → 赋值 let b = null; b ??= "默认值"; // 左边是 null → 赋值 |
||= 左边是假就赋值,&&= 左边是真才赋值,??= 左边是 null / undefined 才赋值。
let n = 0; n ||= 100; console.log(n); // 100(0 被当成"假",被换掉了) let m = 0; m ??= 100; console.log(m); // 0(0 是有效值,保留)
0 和 "" 用 ||= 会被误覆盖,用 ??= 不会。取"默认值"优先用 ??=。