javascript if的优化

1.使用短路逻辑(||   &&)

// 和
let andStr = true && 'Hello AND';
let andStr2 = false && 'Hello AND';
// 或
let orStr = true || 'Hello OR';
let orStr2 = false || 'Hello OR';
2.三元运算符
一些简单的if判断可以使用三元运算符进行代替
a = (a == b) ? c : d;
3.使用按位异或运算符^
var a = 1;
var b = 2;
var c = 1;
if(a == c){
  c = b;
}else if(b == c){
  c = a;
};
//可写成
c = a ^ b ^ c;
4.使用return避免多重if else的嵌套
function(err, results) {
if (!err) {
doMoreSth();
doOtherSth();
// ....sth
// ....sth
return;
}
handleError();
}
5.switch可以使用hash表进行替代
const missionStatus = params.row.missionStatus;
const config = {
1: { status: '待执行', color: '#000099'},
2: { status: '执行中', color: '#0066FF'},
3: { status: '已完成', color: '#008000'},
4: { status: '被取消', color: '#666666'},
5: { status: '失败', color: '#DD5044'},
}
const color = config[missionStatus].color || '', status =
config[missionStatus].status || '';
return h('span', { style: { color: color } }, status);
6.使用ES6 中的Map
const actions = new Map([
[{status: 1, visible: true}, () => {/* **sth** */}],
[{status: 1, visible: false}, () => {/* **sth** */}],
[{status: 2, visible: true}, () => {/* **sth** */}],
[{status: 2, visible: false}, () => {/* **sth** */}],
])
let action = [...actions].filter(([key, value]) => (key.status == status && key
visible == visible));
action.forEach(([key, value]) => value.call(this));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值