js中常忽略了但很实用的运算符(摘选自MDN)

  1. &&= (逻辑与赋值运算符) (x &&= y) //只在x为真时赋值
let x = 0;
let y = 1;
x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0
  1. ||= (逻辑或赋值运算符) (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"
  1. ??= (逻辑空赋值运算符) (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

全部评论

相关推荐

点赞 评论 收藏
分享
烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务