- &&= (逻辑与赋值运算符)
(x &&= y) //只在x为真时赋值
let x = 0; let y = 1; x &&= 0; // 0 x &&= 1; // 0 y &&= 1; // 1 y &&= 0; // 0
- ||= (逻辑或赋值运算符)
(x ||= y) //只在x为假时赋值
const a = { duration: 50, title: '' }; a.duration ||= 10; console.log(a.duration); // expected output: 50 a.title ||= 'title is empty.'; console.log(a.title); // expected output: "title is empty"
- ??= (逻辑空赋值运算符)
(x ??= y) //x 是 nullish (null 或 undefined)时才对x赋值
const a = { duration: 50 }; a.duration ??= 10; console.log(a.duration); // expected output: 50 a.speed ??= 25; console.log(a.speed); // expected output: 25
function config(options) { options.duration ??= 100; options.speed ??= 25; return options; } config({ duration: 125 }); // { duration: 125, speed: 25 } config({}); // { duration: 100, speed: 25 }
MDN相关链接:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators