如何优化if...else嵌套

if(info.type === 'add') {

    cate === 'A' ?
        // add A
        : cate === 'B' ?
        // add B
            : null;

} else if(info.type === 'update') {

    cate === 'A' ?
        // update A
        : cate === 'B' ?
            // update B 
            : null

}

类似于这种,外面是用的if...else内部用的是三元表达式,还有清晰的方案吗?
对于这种多从判断的嵌套,有没有一种优化的思路呢?

阅读 4.7k
8 个回答

要说清晰,我觉得还是原来的程序更清晰。楼上诸位你们自己看看你们的程序,只能说减少了代码量,或者减少了逻辑判断相关的语句而已!清晰?呵呵

switch (cate) {
    case 'a':
        handlerBala(cate, info)
        break;
    case 'b':
        handlerBala(cate, info)
        break;
}

function handlerBala(cate, info) {
    switch (info.type) {
        case 'add':
            add(cate)
            break;
        case 'update':
            update(cate)
            break;
    }
}

单独抽象出去写两个方法 一个add 一个update

cate、type都可扩充的形式,结构清晰。

let obj = {
        A: fn,
        B: fn
    },
    type = {
        'type': 1,
        'update': 1,
        'default': 1
    };

// 通用处理
function fn( t, c ) {
    return t + c;
};

obj[ cate ] && obj[ cate ]( info.type || 'default', cate );
var o={
    add:function(){},
    update:function(){}
}
o[info.type]()
  var a = {
  add: function () { },
  update: function () { }
}

a[info.type]()
var o = {
_methods : function(a, u) {
var s = a + '_' + u;
return s in this ? this[s] : null;
}, 
add_A : 'addA',
add_B : 'addB',
update_A : 'updateA',
update_B : 'updateB'
};
o._methods(info.type, cate);
switch(`${info.type}_${cate}`) {
    case 'add_A': ..
    ...
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题