我的代码片段达到了圈数限制,正在尝试想办法重构。
if(item.oldLabelType === 'Fruits') {
item.newLabel = this._processFruitsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Vegetables') {
item.newLabel = this._processVegetablesLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Animals') {
item.newLabel = this._processAnimalsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Fish') {
item.newLabel = this._processFishLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Birds') {
item.newLabel = this._processBirdsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Colors') {
item.newLabel = this._processColorsLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Countries') {
item.newLabel = this._processCountriesLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Drinks') {
item.newLabel = this._processDrinksLabel(item.oldLabel);
}
else if(item.oldLabelType === 'Cars' || item.oldLabelType === 'Airplanes') {
item.newLabel = this._processTransportationLabel(item.oldLabel);
}
概要 - 我正在重构代码库,后端返回不需要的值,即某些东西的旧标签可能是“仅 1000 美元”,新标签需要“您今天只需支付 1000 美元”。标签操作完全不同,具体取决于发回的 item.oldLabelType。因此,我无法真正编写一个通用的函数来将所有旧标签转换为新标签。
该怎么办!?
最佳答案
这里通常的答案是:
- 使用
开关
(但这并没有太大的改进,或者可以说根本没有改进) - 使用查找
map
或对象 - 使用字符串连接和方括号表示法
这是第三个的样子:
var functionName = item.oldLabelType === 'Cars' || item.oldLabelType === 'Airplanes'
? "_processTransportationLabel"
: "_process" + item.oldLabelType + "Label";
if (this[functionName]) {
item.newLabel = this[functionName](item.oldLabel);
}
关于javascript - 如何重构一个很长的 else if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801872/