美文网首页
js简单优化之大量 if/switch判断

js简单优化之大量 if/switch判断

作者: MiSiTeWang | 来源:发表于2021-05-08 13:58 被阅读0次
    场景
    const title = 0;
    
        if (title == 1) {
            console.log(1);
        }else if(title == 2){
            console.log(2);
        }else if(title == 3){
            console.log(3);
        }else if(title == 4){
            console.log(4);
        }
        ………………
        switch (title) {
            case 1:
                console.log(1);
                break;
            case 2:
                console.log(2);
                break;
            case 3:
                console.log(3);
                break;
            case 4:
                console.log(4);
                break;
        }
        ……
    
    优化
        const actions = {
            1: [1, 11],
            2: [2, 22],
            3: [3, 33],
            4: [4, 44],
        }
        if (actions[title]) {
            console.log(actions[title][0]);
            alert(actions[title][1]);
        }
    
    //es6  Map方法
        const actions = new Map([
            [1, [1, 11]],
            [2, [2, 22]],
            [3, [3, 33]],
            [4, [4, 44]],
            ['default', [0, '00']]
        ])
        const myfunction = (title) => {
            let action = actions.get(title) || actions.get('default')
            console.log(action[0])
            console.log(action[1])
        }
        myfunction(title)
    

    相关文章

      网友评论

          本文标题:js简单优化之大量 if/switch判断

          本文链接:https://www.haomeiwen.com/subject/flhddltx.html