替换javascript swich语句

时间:2015-07-21 17:57:40

标签: javascript

我在javascript中有一个开关,我需要把它区别开来。 如何以更好的方式编写此文件以避免切换?

var types = {   
    Int: 2,
    Short: 3,
    Long: 4,
    Double: 5,  
    Decimal: 6, 
    String: 1,
    Guid: 10,
    Variant: 11,               
};

switch (data.columnTypeId) {

    case types.String:
    case types.Guid:
    case types.Variant:
        self.GetStrings(data);
        break;

    case types.Int:
    case types.Decimal:
    case types.Short:
    case types.Long:                        
    case types.Double:  
        self.GetNumbers(data);
        break;

    default:
}

1 个答案:

答案 0 :(得分:0)

如何做相同的地图,而是映射一个函数引用呢?

var columnTypes = { 
    2: self.GetNumbers,
    3: self.GetNumbers,
    4: self.GetNumbers,
    5: self.GetNumbers,  
    6: self.GetNumbers, 
    1: self.GetStrings,
    10: self.GetStrings,
    11: self.GetStrings,
    0: self.GetDefault //Guessing the default value would be 0          
};

columnTypes[data.columnTypeId](data);

或安全检查:

if (columnTypes.indexOf(data.columnTypeId) !== -1) {
    columnTypes[data.columnTypeId](data);
} else {
    self.GetDefault(data);
}

或者@dandavis在评论中指出:

columnTypes[data.columnTypeId || self.getDefault](data);