4个强大JavaScript运算符
WEB前端开发社区 2021-07-20
null ?? 5 // => 53 ?? 5 // => 3
var prevMoney = 1var currMoney = 0var noAccount = nullvar futureMoney = -1function moneyAmount(money) {return money || `账户未开通`}console.log(moneyAmount(prevMoney)) // => 1console.log(moneyAmount(currMoney)) // => 账户未开通console.log(moneyAmount(noAccount)) // => 账户未开通console.log(moneyAmount(futureMoney)) // => -1
var currMoney = 0var noAccount = nullfunction moneyAmount(money) { return money ?? `账户未开通`}moneyAmount(currMoney) // => 0moneyAmount(noAccount) // => `账户未开通`
var x = nullvar y = 5console.log(x ??= y) // => 5console.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 = 0var transportion = (budget > 0) ? '火车' : '步行' console.log(transportion) // => '步行'
var x = 6var x = (x !== null || x !== undefined) ? x : 3console.log(x) // => 6
function nullishAssignment(x,y) { return (x == null || x == undefined) ? y : x }nullishAssignment(null, 8) // => 8nullishAssignment(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;}
赞 (0)