Fork me on github

优化if-else,switch-case

钩子函数

说明:条件与值一一对应

注:代替if-else,switch-case,提高程序运行效率,hook机制也就是钩子机制,由表驱动实现,常用来处理多种特殊情况的处理

  let list = {
        '1':'test1',
        '2':'test2',
        '3':'test3',
        '4':'test4',
    }
    var code = 4
    if(code){
        alert(list[code])
    }
var arr = [{name: 'liming', score: 70, praise: 1},
 {name: 'liyi', score: 90, praise: 2},
 {name: 'liuwei', score: 80, praise: 3},
 {name: 'ertuzi', score: 85, praise: 3}]
 var rule = {
        1:20,
        2:10,
        3:5
    }
arr.forEach((item,index)=>{
   if(item.praise)
   item.score += rule[item.praise]
})
console.log(arr) //此处修改原数组

简单分支优化

说明:条件与处理函数一一对应

    function getUserDescribe(name) {
    const describeForNameMap = {
        小刘: () => console.log("刘哥哥"),
        小红: () => console.log("小红妹妹"),
        陈龙: () => console.log("大师"),
        李龙: () => console.log("师傅"),
        大鹏: () => console.log("恶人"),
    };
    describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!");
}

复杂分支优化

 注:引入二维数组,(条件较复杂)

function getUserDescribe(name) {
    const describeForNameMap = [
        // 判断条件,执行函数
        [(name) => name.length > 3, () => console.log("名字太长")],
        [(name) => name.length < 2, () => console.log("名字太短")],
        [(name) => name[0] === "陈",() => console.log("小陈")],
        [(name) => name === "大鹏",() => console.log("管理员")],
        [(name) => name[0] === "李" && name !== "李鹏",() => console.log("小李"),],
    ];
    // 获取符合条件的子数组
    const getDescribe = describeForNameMap.find((item) => item[0](name));
    // 子数组存在则运行子数组中的第二个元素(执行函数)
    getDescribe ? getDescribe[1]() : console.log("此人比较神秘!");
}

 

posted @ 2022-08-19 14:23  我の前端日记  阅读(66)  评论(0编辑  收藏  举报
Copyright © 2021 LinCangHai
Powered by .NET 5.0 on Kubernetes