前端代码优化 - 如何在代码中减少if else语句的使用

使用&&/||

if(conected){
    login();
}
//上述可以简写为:conected &&  login();

if(a为真){
    a=a
}else{
    a=b
}
//上述可以简写为:a = a || b

使用三元表达式

if(a==b){
    a=c
}else{
    a=d
}
可写成:a = (a==b) ? c : d

使用switch/case

$.ajax().done(function (res) {
    if (res.state === 'SUCCESS') {
        //TODO
    } else if (res.state === 'FAIL') {
        //TODO
    } else {
        //TODO
    }
});
可改写成:(千万不要忘记在每一个case语句后面放一个break语句。也可以放一个return或者throw。case语句匹配expression是用===而不是==)
$.ajax().done(function (res) {
    switch (res.state) {
        case 'SUCCESS':
            //TODO
            break;
        case 'FAIL':
            //TODO
            break;
        default :
            //TODO
    }
});

使用hash 表

if (key == "Apple") {
    val = "Jobs";
} else if (key == "microsoft"){
    val = "Gates";
} else if (key == "Google"){
    val = "Larry";
}
可改写成:
var ceos = {"Apple":"Jobs", "microsoft":"Gates", "Google":"Larry"};
val = ceos[key];

对象重构,用 OO 里面的继承或者组合

function getName(type) {
    if (type === 'monkey') {
        return 'monkey name';
    } else if (type === 'cat') {
        return 'cat name';
    } else {
        return 'dog name';
    }
}
可改写成:
function getName(type) {
    var data = {
        monkey: 'monkey name',
        cat: 'cat name',
        dog: 'dog name'
    }
    return data[type] ? data[type] : data['dog'];
}

原文链接:https://www.cnblogs.com/zuobaiquan01/p/5766749.html

posted @ 2020-11-04 09:12  JaneLifeVlog  阅读(347)  评论(0)    收藏  举报