提升开发效率小技巧(js2)

165 阅读1分钟

提升开发效率小技巧(js2)

字典代替switch case

假设我们的应用程序中有一个过滤器逻辑。处理这种情况,我们一般最常用的方法是使用switch case语句。

let type = "item1";
switch(type){
    case "item1":
        type = "item1";
        break;
    case "item2":
        type = "item2";
        break;
    case "item3":
        type = "item3";
        break;
    default:
        type = "item1";
}

使用这种方法没有什么问题。但是上面的例子中,我们只关心访问的是谁,顺序并不是很重要的时候,使用字典可能不失为一种更好的选择。在JavaScript中,对象

const type = "item1";
const filterDictionary = {
    type1: "item1",
    type2: "item2",
    type3: "item3"
}
type = filterDictionary[type];