4 个强大的 JavaScript 运算符
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) // => `账户未开通`
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}
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
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 进行转义,解决浏览器兼容性问题)
延伸阅读
https://medium.com/javascript-in-plain-english/4-powerful-javascript-operators-youve-never-heard-of-487df37114ad
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂大佬的经验
、增长自身
、学习资料
、职业路线
、赚钱思维
,微信搜索逆锋起笔
关注!
今日荐文
评论