你有沒有花一個下午的時間閱讀 Mozilla 文檔?如果有,你會發現網上有很多 JS 資料,這使我們很容易忽略那些更為基礎的 JS 運算符。
這些運算符不常見但很強大!在語法上看起來很相似,作用卻不一樣,一定要仔細閱讀。
在 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
var currMoney = 0
var noAccount = null
function moneyAmount(money) {
return money ?? `帳戶未開通`
}
moneyAmount(currMoney) // => 0
moneyAmount(noAccount) // => `帳戶未開通`
概括地說 ?? 運算符允許我們在忽略錯誤值(如 0 和空字符串)的同時指定默認值。
var x = null
var y = 5
console.log(x ??= y) // => 5
console.log(x = (x ?? y)) // => 5
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}
上述函數處理空值的方式有一個值得注意的區別。默認參數將用空參數(譯者注,這裡的空參數,只能是 undefined)覆蓋默認值,空賦值運算符將不會。默認參數和空賦值都不會覆蓋未定義的值。更多:
在公眾號頂級架構師後臺回復「架構整潔」,獲取一份驚喜禮包。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
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
上面的例子包含了我們到目前為止所學的所有運算符。現在我們已經創建了一個函數,該函數將計劃添加到當前沒有嵌套屬性的對象 tuesday.location 中。我們還使用了非空運算符來提供默認值。此函數將錯誤地接受像「0」這樣的值作為有效參數。這意味著 budget 可以設置為零,沒有任何錯誤。
function checkCharge(charge) {
return (charge > 0) ? '可用' : '需充值'
}
console.log(checkCharge(20)) // => 可用
console.log(checkCharge(0)) // => 需充值
var budget = 0
var transportion = (budget > 0) ? '火車' : '步行'
console.log(transportion) // => '步行'
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;
}
我們現在已經學習了這些運算符的使用方法,在這裡有更多關於這些運算符的知識。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators
(譯者註:文中前三個運算符是 ES2020 的新特性,請勿直接用在生產環境, 可使用 webpack+babel 進行轉義,解決瀏覽器兼容性問題)
PS:歡迎在留言區留下你的觀點,一起討論提高。如果今天的文章讓你有新的啟發,歡迎轉發分享給更多人。版權申明:內容來源網絡,版權歸原創者所有。除非無法確認,我們都會標明作者及出處,如有侵權煩請告知,我們會立即刪除並表示歉意。謝謝!