js中.?、??、??=、!、!!……

165 阅读2分钟

可选链(.?)

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

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};
// 可选链和对象
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
// 可选链和函数
adventurer.someNonExistentMethod?.();

参考

空值合并运算符(??)

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

逻辑或操作符(||不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。见下面的例子

const foo = null ?? 'default string';
console.log(foo); // "default string"

const baz = 0 ?? 42;
console.log(baz); //  0

空值赋值运算符(??=)

当??=左侧的值为null、undefined的时候,才会将右侧变量的值赋值给左侧变量.其他所有值都不会进行赋值.同样在一些场景下,可以省略很多代码.

let b = '你好'; 
let a = 0 
let c = null; 
let d = ’123‘ 
b ??= a; // b = “你好” 
c ??= d // c = '123'

逻辑非(!)

null、undifined、0、empty string ("" or '' or ``)、NaN会转为false;其他都会转为true;

运算符(!!)

var a;
if(a!=null&&typeof(a)!=undefined&&a!=''){
    //a有内容才执行的代码  
}
if(!!a){
    //a有内容才执行的代码...  
}

“!”是逻辑与运算,并且可以与任何变量进行逻辑与将其转化为布尔值,“!!”则是逻辑与的取反运算, 尤其后者在判断类型时代码简洁高效,省去了多次判断null、undefined和空字符串的冗余代码。