常用的js判断简写技巧

发布时间 2023-06-01 15:08:36作者: 无序

空值合并运算符(??)是一个逻辑运算符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

function(obj){
  var b = obj ?? {}
}
// 等价于 =>>
function(obj){
  var b;
  if(
    obj === null || 
    obj === undefined
  ){
     b = {}
   } else {
     b = obj;
  }
}

可选链运算符?.)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 运算符的功能类似于 . 链式运算符,不同之处在于,在引用为空 (nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

const student = {
  name: "Joy",
  age: 28,
  address: {
    state: "Hong Kong"
  },
};

// LONG FORM
console.log(student && student.address && student.address.ZIPCode); // Doesn't exist - Returns undefined
// SHORTHAND
console.log(student?.address?.ZIPCode); // Doesn't exist - Returns undefined

逻辑空赋值运算符(x ??= y仅在 x 是空值null 或 undefined)时对其赋值。

const a = { c: 50 };

a.c??= 10;
console.log(a.c);
// expected output: 50

a.speed ??= 33;
console.log(a.speed);
// expected output: 33