4 個強大 JavaScript 運算符

1. ?? 非空運算符

在 JS 中,?? 運算符被稱爲非空運算符。如果第一個參數不是 null/undefined(譯者注:這裏只有兩個假值,但是 JS 中假值包含:未定義 undefined、空對象 null、數值 0、空數字 NaN、布爾 false,空字符串’’,不要搞混了),將返回第一個參數,否則返回第二個參數。比如,

null ?? 5 // => 5
3 ?? 5 // => 3

給變量設置默認值時,以前常用 ||邏輯或運算符,例如,

var prevMoney = 1
var currMoney = 0
var noAccount = null
var futureMoney = -1
function moneyAmount(money) {
return money || `賬戶未開通`
}
console.log(moneyAmount(prevMoney)) // => 1
console.log(moneyAmount(currMoney)) // => 賬戶未開通
console.log(moneyAmount(noAccount)) // => 賬戶未開通
console.log(moneyAmount(futureMoney)) // => -1

上面我們創建了函數 moneyAmount,它返回當前用戶餘額。我們使用 || 運算符來識別沒有帳戶的用戶。然而,當用戶沒有帳戶時,這意味着什麼?將無賬戶視爲空而不是 0 更爲準確,因爲銀行賬戶可能沒有(或負)貨幣。在上面的例子中,|| 運算符將 0 視爲一個虛假值,不應該包括用戶有 0 美元的帳戶。讓我們使用?? 非空運算符來解決這個問題:

var currMoney = 0
var noAccount = null
function moneyAmount(money) {
  return money ?? `賬戶未開通`
}
moneyAmount(currMoney) // => 0
moneyAmount(noAccount) // => `賬戶未開通`

2. ??= 空賦值運算符

var x = null
var y = 5
console.log(x ??= y) // => 5
console.log(x = (x ?? y)) // => 5

僅當值爲 null 或 undefined 時,此賦值運算符纔會賦值。上面的例子強調了這個運算符本質上是空賦值的語法糖(譯者注,類似的語法糖:a = a + b 可寫成 a += b )。接下來,讓我們看看這個運算符與默認參數(譯者注,默認參數是 ES6 引入的新語法,僅當函數參數爲 undefined 時,給它設置一個默認值)的區別:

function gameSettingsWithNullish(options) {
  options.gameSpeed ??= 1
  options.gameDiff ??= 'easy' 
  return options
}
function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') {
  return {gameSpeed, gameDiff}
}
gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => {gameSpeed: 1, gameDiff: 'easy'}
gameSettingsWithDefaultParams(undefined, null) // => {gameSpeed: null, gameDiff: null}

3. ?. 鏈判斷運算符

鏈判斷運算符?. 允許開發人員讀取深度嵌套在對象鏈中的屬性值,而不必驗證每個引用。當引用爲空時,表達式停止計算並返回 undefined。比如:

var travelPlans = {
  destination: 'DC',
  monday: {
    location: 'National Mall',
    budget: 200
  }
}
console.log(travelPlans.tuesday?.location) // => undefined
function addPlansWhenUndefined(plans, location, budget) {
  if (plans.tuesday?.location == undefined) {
    var newPlans = {
      plans,
      tuesday: {
        location: location ?? "公園",
        budget: budget ?? 200
      },
    }
  } else {
    newPlans ??= plans; // 只有 newPlans 是 undefined 時,才覆蓋
    console.log("已安排計劃")
  }
  return newPlans
}
// 譯者注,對象 travelPlans 的初始值,來自上面一個例子
var newPlans = addPlansWhenUndefined(travelPlans, "Ford 劇院", null)
console.log(newPlans)
// => { plans: 
// { destination: 'DC',
// monday: { location: '國家購物中心', budget: 200 } },
// tuesday: { location: 'Ford 劇院', budget: 200 } }
newPlans = addPlansWhenUndefined(newPlans, null, null)
// logs => 已安排計劃
// returns => newPlans object

4. ?: 三元運算符

var x = 6
var x = (x !== null || x !== undefined) ? x : 3
console.log(x) // => 6
function nullishAssignment(x,y) {
  return (x == null || x == undefined) ? y : x 
}
nullishAssignment(null, 8) // => 8
nullishAssignment(4, 8) // => 4
function addPlansWhenUndefined(plans, location, budget) {
 var newPlans =
   plans.tuesday?.location === undefined
     ? {
         plans,
         tuesday: {
           location: location ?? "公園", 
           budget: budget ?? 200
         },
       }
     : console.log("已安排計劃");
 newPlans ??= plans;
 return newPlans;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章