?.、??、??=的用法和含义

166 阅读1分钟
let a;
let b = a?.name // b = undefined

?.叫做可选符,只有当a存在,同时a具有name属性的时候,才会把值赋给b,否则就会将undefined赋值给b。最重要的是,不管a存在与否,这么做都不会报错!

let b;
let a = 0;
let c = { name: 'qq'}

b = a ?? c // b = 0

??是空值合并运算符,当a是除了undefined或null之外的任何值,b都等于a,否则就等于c。

let b = 'hello';
let a = 0;
let c = null;
let d = '123';

b ??= a; // b= "hello"
c ??= d; // c= "123"

??=为空值赋值运算符,当??=左边的值为undefined或者nul的时候,才会将右侧变量的值赋值给左侧变量,其他所有制都不会进行赋值。