JavaScript 表达式与运算符全解析
1. 条件属性访问
在 JavaScript 中,可以使用 ?.[] 替代 [] 进行条件属性访问。在表达式 a?.[b][c] 里,如果 a 的值为 null 或者 undefined ,那么整个表达式会立即求值为 undefined ,并且子表达式 b 和 c 都不会被求值。示例代码如下:
let a; // Oops, we forgot to initialize this variable!
let index = 0;
try {
a[index++]; // Throws TypeError
} catch(e) {
console.log(index); // => 1: increment occurs before TypeError is thrown
}
console.log(a?.[index++]); // => undefined: because a is undefined
console.log(index); // => 1: not incremented because ?.[] short-circuits
console.log(a[index++]); // !TypeErr
JavaScript表达式与运算符全解析
超级会员免费看
订阅专栏 解锁全文
3

被折叠的 条评论
为什么被折叠?



