&&=、||= 和 ??= 有什么用途? [英] What purpose do &&=, ||= and ??= serve?

查看:64
本文介绍了&&=、||= 和 ??= 有什么用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 v15.0.1:&&=||=??=.但我不知道它有什么作用.有人知道吗?

I have seen this syntax in node.jsv15.0.1: &&=, ||= and ??=. But I don't know what it does. Does anyone know?

推荐答案

这些是新的 logical赋值运算符.它们类似于更熟悉的运算符,例如 *=+= 等.

These are the new logical assignment operators. They're similar to the more familiar operators like *=, +=, etc.

someVar &&= someExpression 大致相当于 someVar = someVar &&someExpression.

someVar ||= someExpression 大致相当于 someVar = someVar ||someExpression.

someVar ??= someExpression 大致相当于 someVar = someVar ??someExpression.

我说大致"因为有一个区别——如果不使用右侧的表达式,则不会调用可能的 setter.所以它更接近于:

I say "roughly" because there's one difference - if the expression on the right-hand side isn't used, possible setters are not invoked. So it's a bit closer to:

someVar &&= someExpression 就像

if (!someVar) {
  someVar = someExpression;
}

等等.(不调用 setter 的事实不太可能有影响在脚本中,但这并非不可能.)这与其他传统的速记赋值运算符不同,它们 无条件赋值给变量或属性(从而调用 setter).下面是一个演示片段:

and so on. (The fact that a setter isn't invoked is unlikely to have an effect on the script, but it's not impossible.) This is unlike the other traditional shorthand assignment operators which do unconditionally assign to the variable or property (and thus invoke setters). Here's a snippet to demonstrate:

const obj = {
  _prop: 1,
  set prop(newVal) {
    this._prop = newVal;
  },
  get prop() {
    return this._prop;
  }
};

// Setter does not get invoked:
obj.prop ||= 5;

??,如果你不熟悉的话,就是空合并运算符.如果左侧是 nullundefined,它将评估右侧.

??, if you aren't familiar with it, is the nullish coalescing operator. It will evaluate to the right-hand side if the left-hand side is either null or undefined.

这篇关于&&=、||= 和 ??= 有什么用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆