x ||= y
逻辑或赋值运算符 ||=
的含义是:如果 x 为假,将 y 赋值给 x,即:
if (!x) {
x = y
}
逻辑或赋值 ||=
的应用:
const a = { duration: 50, title: '' };
a.duration ||= 10;
console.log(a.duration); // 50
a.title ||= 'title is empty.';
console.log(a.title); // "title is empty"
x &&= y
逻辑与赋值运算符 &&=
的含义是:如果 x 为真,将 y 赋值给 x,即:
if (x) {
x= y
}
逻辑与赋值运算符 &&=
的应用:
const a = { duration: 50, title: '' };
a.duration &&= 10;
console.log(a.duration); // 10
a.title &&= 'title is empty.';
console.log(a.title); // ""
x ??= y
逻辑空赋值运算符 x ??= y
的含义是:如果 x 为空值(null
或 undefined
),将 y 赋值给 x,即
if (x === null || x === undefined) {
x = y
}
逻辑空赋值运算符 ??=
的应用:
const a = { duration: 50, title: '' };
a.duration ??= 10;
console.log(a.duration); // 50
a.title ??= 'title is empty.';
console.log(a.title); // ""
可选链 ?. 有什么用?
面试高频指数:★★★☆☆
MDN 上对可选链的定义:
可选链运算符(?.)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?. 运算符的功能类似于 . 链式运算符,不同之处在于,在引用为空 (null 或者 undefined) 的情况下不会引起错误,返回 undefined。
可选链可以帮助我们减少判断有效值的代码,特别是深层嵌套对象下访问某个属性,如果属性不存在,不会引起错误。
如果调用对象上不存在的函数,会报错,如下图:
如果使用 ?. 判断函数调用,就不会报错,如面代码:
let person = {
name: "zhangsan",
details: { age: 20 }
}
console.log(person.getGender?.())
空值合并操作符可以在使用可选链时设置一个默认值:
let person = {
name: "zhangsan",
details: { age: 20 }
}
let add = person?.city ?? '默认值';
console.log(add) // '默认值'
作者:LeetCode
链接:https://leetcode.cn/leetbook/read/javascript-interview-2/7m7w0v/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
阅读量:1971
点赞量:0
收藏量:0