JS的可選鏈操作符(?.)與雙問號(??),你用到了嗎?


可選鏈操作符(?.)

以前一般這樣使用:

let nestedProp = obj.first && obj.first.second;

或者這樣:

let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);

現在我們這樣使用:

let nestedProp = obj.first?.second; // 訪問屬性
let result = someInterface.customMethod?.(); // 調用方法
let nestedProp = obj?.['prop' + 'Name']; // 表達式
let arrayItem = arr?.[42]; // 訪問數組

詳細使用可參考:Optional chaining (?.)

雙問號(??)

語法:

leftExpr ?? rightExpr

??在leftExpr和rightExpr之間,只有當leftExprnull或者 undefined時取rightExpr,否則取leftExpr0,false,""被認為是有意義的,所以還是取leftExpr

以前這樣使用:

let foo;
let someDummyText = foo || 'Hello!';

基礎示例:

const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42

特殊示例:

null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError

(null || undefined) ?? "foo"; // returns "foo"

詳細使用可參考:Nullish coalescing operator (??)

工程中怎樣使用

babel7以上版本支持,可以添加以下2個devDependencies依賴:

@babel/plugin-proposal-optional-chaining // 可選鏈
@babel/plugin-proposal-nullish-coalescing-operator // 雙問號

.babelrc或者babel.config.js中這加入2個插件(plugins屬性放在JSON頂層):

{
 "plugins": [
    "@babel/plugin-proposal-nullish-coalescing-operator",
    "@babel/plugin-proposal-optional-chaining"
  ]
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM