带有if的代码简化
function validation(customer) {
if (!customer.email) {
return error('email is require')
} else if (!customer.login) {
return error('login is required')
} else if (!customer.name) {
return error('name is required')
} else {
return customer;
}
}
重构后的代码
const customerValidation = customer =>
!customer.email ? error('email is required')
: !customer.login ? error('login is required')
: !customer.name ? error('name is required')
: customer ;
短路运算符1
if(name){
login(name) //执行
}
重构
name&&login(name);
短路运算符2
if(name&&password){
login(name,password) //执行
}
重构后
var name = true;
var password = '001'
function login(name,password){
console.log('登录成功')
}
name&&password && login(name,password);
swich的代码
var day;
switch (new Date().getDay()) {
case 0:
day = "周日";
break;
case 1:
day = "周一";
break;
case 2:
day = "周二";
break;
case 3:
day = "周三";
break;
case 4:
day = "周四";
break;
case 5:
day = "周五";
break;
case 6:
day = "周六";
}
console.log(day)
重构后
const nowWeek = (day) => ({
'0':'周日',
'1':'周一',
'2':'周二',
'3':'周三',
'4':'周四',
'5':'周五',
'6':'周六',
})[day] || '其他'
var a = nowWeek(1);
console.log(a) //周一
// 例子一个函数返回一个对象
const aa = (day) => ({
'0':'周一'
})
console.log(aa(0))
const bb = (day) => {
return {
'0':'周一'
}
}
console.log(bb(0))