js 多分支结构优化

数据映射快速匹配 实现 通过数组/普通对象

情况 条件体的数量庞大

 

function map(value) {
    switch (value) {
        case 0 : return "result0";
        case 1 : return "result1";
        case 2 : return "result2";
        case 3 : return "result3";
        case 4 : return "result4";
        case 5 : return "result5";
        case 6 : return "result6";
        case 7 : return "result7";
        case 8 : return "result8";
        case 9 : return "result9";
        default : return "result10"
    }
}

 

通过数组下标

function map(value) {
    var results = ["result0","result1","result2","result3","result4","result5",
                   "result6","result7","result8","result9","result10"]
    return results[value];
}

 

如果条件查询中键名不是有序数字,则无法与数组下标映射,这时可以使用对象数据映射法。

function map(value) {
    var results = {
        "a" : "result0","b" : "result1","c" : "result2","d" : "result3","e" : "result4","f" : "result5",
        "g" : "result6","h" : "result7","i" : "result8","j" : "resukt9","k" : "result10"
    }
    return results[value];
}

 

posted @ 2020-10-19 18:50  啾啾啾啾一口  阅读(271)  评论(0编辑  收藏  举报