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); // ""