4

JavaScript 逻辑赋值运算符

 1 year ago
source link: https://www.myfreax.com/javascript-logical-assignment-operators/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript 逻辑赋值运算符

JavaScript 逻辑赋值运算符

在本教程中,您将了解 JavaScript 逻辑赋值运算符,包括逻辑或赋值运算符 ||=、逻辑与赋值运算符 &&= 和空值赋值运算符 ??=

ES2021 引入了三个逻辑赋值运算符,包括:

  • 逻辑或赋值运算符 ||=
  • 逻辑与赋值运算符 &&=
  • 无效合并赋值运算符  ??=

下表显示了逻辑赋值运算符与逻辑运算符的等价表达式。

逻辑赋值运算符逻辑运算符
x ||= yx|| (x = y)
x &&= yx && (x = y)
x ??= yX ??(x = y);

逻辑或赋值运算符

逻辑或赋值运算符 ||= 接受两个操作数,如果左操作数为假,则将右操作数分配给左操作数:

x ||= y

在此语法中,||= 运算符仅在 x 假时 y 才赋值 x 。例如:

let title;
title ||= 'untitled';

console.log(title);
untitled

在这个例子中,title 变量是 undefined,因此它是假的。由于 title 是假的,运算符 ||='untitled' 赋值给 title。输出打印 untitled ,和预期的一致。

看另一个例子:

let title = 'JavaScript Awesome';
title ||= 'untitled';

console.log(title);
'JavaScript Awesome'

在这个例子中, title 值是 'JavaScript Awesome' 所以title 是真值。因此,逻辑或赋值运算符 ||= 不会将字符串 'untitled' 赋给 title 变量。

逻辑或赋值运算符:

x ||= y

等效于以下使用逻辑或运算符的语句:

x || (x = y)

与逻辑或运算符一样,逻辑或赋值也会短路评估。这意味着逻辑或赋值运算符仅在 x 为假时执行赋值。

以下示例使用逻辑赋值运算符在搜索结果元素为空时显示默认消息:

document.querySelector('.search-result').textContent ||= 'Sorry! No result found';

逻辑与赋值运算符

逻辑与赋值运算符仅在 x 为真时,将 y 赋值 x

x &&= y;

逻辑与赋值运算符也会短路。

x &&= y;
x && (x = y);

以下示例使用逻辑与赋值运算符修改 person 对象的 lastName,当 lastName 为真值时:

let person = {
    firstName: 'Jane',
    lastName: 'Doe',
};

person.lastName &&= 'Smith';

console.log(person);
{firstName: 'Jane', lastName: 'Smith'}

无效合并赋值运算符

无效合并赋值运算符仅在 x 是 null 或者 undefined  时,将 y 赋值给x

x ??= y;

它等效于以下使用无效合并运算符的语句:

x ?? (x = y);

以下示例使用无效合并赋值运算符将缺少的属性添加到对象:

let user = {
    username: 'Satoshi'
};
user.nickname ??= 'anonymous';

console.log(user);
{username: 'Satoshi', nickname:'anonymous'}

在这个例子中,user.nicknameundefined,因此,它是无效的。无效合并赋值运算符将字符串 'anonymous'  分配给属性 user.nickname

  • 逻辑或赋值运算符  x ||= y 仅在 x 为假时才将 y 赋值 x
  • 逻辑与赋值运算符 x &&= y 仅在 x 为真时才将y 赋值 x
  • 空值合并赋值运算符 x ??= y 仅在 x 为空时,才将 y 赋值 x

微信公众号

支付宝打赏

myfreax 淘宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK