# 如何优化if多层判断

• 4
``````aa(item) {
let color;
let eq1 = "";
let eq2 = "";

for (let i = 0; i < this.option.columnTow.length; i++) {
let element = this.option.columnTow[i];
console.log(parseInt(eq1) < parseInt(item.value))
if (eq1 != "" && eq2 != "" && parseFloat(eq1) < parseFloat(item.value) && parseFloat(item.value) < parseFloat(eq2)) {
color = element.prop;
break;
}
else if (eq1 != "" && eq2 != "" && parseFloat(eq2) < parseFloat(eq1)) {
if (element.equation == "大于" && parseFloat(item.value) > parseFloat(element.value)) {
color = element.prop;
break;
}
else if (element.equation == "小于" && parseFloat(item.value) < parseFloat(element.value)) {
color = element.prop;
break;
}
}
if (element.equation == "大于" && eq2 == "" && parseFloat(item.value) > parseFloat(element.value)) {
color = element.prop;
break;
}
if (element.equation == "小于" && eq1 == "" && parseFloat(item.value) < parseFloat(element.value)) {
color = element.prop;
break;
}
if (element.equation == "等于" && parseFloat(item.value) == parseFloat(element.value)) {
color = element.prop;
break;
}
}
return color;
}``````

5 个回答

## 扁平化

``````    if (eq1 !="" && eq2 !="" &&   parseFloat(eq1) < parseFloat(item.value) && parseFloat(item.value)  < parseFloat(eq2) ){
color= element.prop;
break;
}
else if``````

``````if (xxx) {
color = element.prop;
break;
}
// 后面的计算
if (ooo) {

}
...``````

## 具体化

``````const isMeathillGoodLookAndKindHearted = meathill
&& meathill.isGoodLook()
&& meathill.isKindHearted();
if (isMeathillGoodLookAndKindHearted) {
giveMoneyTo(meathill);
}``````