发布于 2026-01-06 0 阅读
0

JavaScript 中的逻辑赋值运算符

JavaScript 中的逻辑赋值运算符

JavaScript 中的逻辑赋值运算符结合了逻辑运算符和赋值表达式。

//"Or Or Equals"
x ||= y;
x || (x = y);
Enter fullscreen mode Exit fullscreen mode
// "And And Equals"
x &&= y;
x && (x = y);
Enter fullscreen mode Exit fullscreen mode
// "QQ Equals"
x ??= y;
x ?? (x = y);
Enter fullscreen mode Exit fullscreen mode

假设你有一个函数,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
}
Enter fullscreen mode Exit fullscreen mode

你也可以把它和……一起使用??

function setOpts(opts) {
  opts.cat ??= 'meow'
  opts.dog ??= 'bow';
}

setOpts({ cat: 'meow' })
Enter fullscreen mode Exit fullscreen mode

这是第四阶段,您今天应该就能用了!

我很高兴能够共同发起这项提案。

7年前,这只是一个想法!

历史

文章来源:https://dev.to/hemanth/logic-assignment-operators-in-javascript-inh