Javascript中的逻辑赋值操作
逻辑赋值操作就是把逻辑操作和赋值操作合在一起:
//"Or Or Equals" x ||= y; x || (x = y); // "And And Equals" x &&= y; x && (x = y); // "QQ Equals" x ??= y; x ?? (x = y);
所以当你些一个UpdateId的函数的时候,可以这样写:
const updateID = user => {
// We can do this
if (!user.id) user.id = 1
// Or this
user.id = user.id || 1
// Or use logical assignment operator.
user.id ||= 1
}
你现在也可以使用??来实现了:
function setOpts(opts) {
opts.cat ??= 'meow'
opts.dog ??= 'bow';
}
setOpts({ cat: 'meow' })
这个feature目前在stage-4中支持,我想你应该可以使用了。

Recent Comments