避免几个嵌套的if语句

时间:2018-08-17 13:52:39

标签: javascript if-statement nested code-cleanup

我正在编写一个函数,该函数根据4个变量的状态将特定(预定义)变量推入预定义数组,所有变量的范围从1到5(它们是在我们的网页上按下的单选按钮的结果)

如果变量等于A,B,C和D,则通过以下方式定义预定义数组X,Y和Z的预定义变量:

X = A和B的组合。

Y = C和D的组合。

Z = A,B,C和D的组合。

下面是我使用嵌套的if / else语句来实现上述问题的解决方案(A,B,C和D是动机,方向,影响和相关性)。但是,我发现此解决方案不理想。我俩都想编写更简洁的代码,并让我的同事对代码更具可读性。什么是最优雅的输入方式?我应该使用函数,switch语句等吗?

下面是整个功能:

function getRadioParameters (influence, relevance, motivation, orientation) {
    if (influence >= 3) {
        if (relevance >= 3) {
            influenceRelevanceArr.push(highInfluenceHighRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('HHHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('HHHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('HHLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('HHLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else if (relevance < 3) {
            influenceRelevanceArr.push(highInfluenceLowRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('HLHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('HLHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('HLLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('HLLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else {
            influenceRelevanceArr.push('');
            motivationOrientationArr.push('');
            stkImagesArr.push('');
            console.log('problem with relevance. It is =', relevance);
        }
    }
    else if (influence < 3) {
        if (relevance >= 3) {
            influenceRelevanceArr.push(lowInfluenceHighRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('LHHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('LHHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('LHLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('LHLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else if (relevance < 3) {
            influenceRelevanceArr.push(lowInfluenceLowRelevance);
            if (motivation >= 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(highMotivationHighOrientation);
                    stkImagesArr.push(getImage('LLHH'));
                }
                else if (orientation < 3) {
                    motivationOrientationArr.push(highMotivationLowOrientation);
                    stkImagesArr.push(getImage('LLHL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation)
                }
            }
            else if (motivation < 3) {
                if (orientation >= 3) {
                    motivationOrientationArr.push(lowMotivationHighOrientation);
                    stkImagesArr.push(getImage('LLLH'));
                }
                else if (orientation<3) {
                    motivationOrientationArr.push(lowMotivationLowOrientation);
                    stkImagesArr.push(getImage('LLLL'));
                }
                else {
                    motivationOrientationArr.push('');
                    stkImagesArr.push('');
                    console.log('problem with orientation. It is = ', orientation);
                }
            }
            else {
                motivationOrientationArr.push('');
                stkImagesArr.push('');
                console.log('problem with motivation. It is = ', motivation);
            }

        }
        else {
            influenceRelevanceArr.push('');
            motivationOrientationArr.push('');
            stkImagesArr.push('');
            console.log('problem with relevance. It is =', relevance);
        }
    }

}

谢谢!

3 个答案:

答案 0 :(得分:0)

以下是使用函数将其抽象化的示例:

//X = the combination of A and B.
//Y = the combination of C and D.
//Z = the combination of A, B, C and D.
// in this example:
// A > 5, B > 10, C> 15, D > 20

function returnCharacteristic(input) {
  if (input[0] > 5 && input[1] > 10 && input[2] > 15 && input[3] > 20) {
    return 'Z';
  }
  if (input[2] > 15 && input[3] > 20) {
    return 'Y';
  }
  if (input[0] > 5 && input[1] > 10) {
    return 'X';
  }
  
  return 'No criterea met';


}

let test1 = [10, 5, 33, 5];
let test2 = [10, 15, 32, 50];
let test3 = [20, 20, 10, 9];
let test4 = [0, 5, 50, 50];


console.log(returnCharacteristic(test1));
console.log(returnCharacteristic(test2));
console.log(returnCharacteristic(test3));
console.log(returnCharacteristic(test4));

在此示例中,我使用了一些随机条件来确定是否满足某个条件,但是您当然需要根据自己的需求进行调整。通常,当您的代码像您一样深深地嵌套时,您就犯了一个代码设计错误。通常,会有更优雅的解决方案,要求您稍微重构代码。

深层嵌套的代码增加了对其进行推理的难度,这不仅使您的代码难以维护,而且增加了引入错误的机会。而且即使存在错误,也很难调试深度嵌套的代码。

希望这会有所帮助。

答案 1 :(得分:0)

分别获得每个值然后以某种方式组合它们可能会更容易-这完全取决于您的数据结构。到目前为止,我认为您可以执行以下操作(这是高级操作,您必须自己填写所有详细信息):

function getRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'highInfluence', 'lowInfluence');
  const rel = gague(relevance, 'highRelevance', 'lowRelevance');
  const mot = gague(motivation, 'highMotivation', 'lowMotivation');
  const ori = gague(orientation, 'highOrientation', 'lowOrientation');
  const allVals = [inf, rel, mot, ori];
  const finalValues = getFinalValues(allVals);

  return finalValues;
}

function getFinalValues(allVals) {
  const finalValues = { img: '', char: '' };

  allVals.forEach(function(item) {
    finalValues.img += item.img;
    finalValues.char += item.char;
  });

  return finalValues;
}

function gague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);

此外,如果您使用的是ES6 / 7,则可以进一步简化代码:

function getRadioParameters(influence, relevance, motivation, orientation) {
  const inf = gague(influence, 'HIGH-influence', 'LOW-influence');
  const rel = gague(relevance, 'HIGH-relevance', 'LOW-relevance');
  const mot = gague(motivation, 'HIGH-motivation', 'LOW-motivation');
  const ori = gague(orientation, 'HIGH-orientation', 'LOW-orientation');
  const allVals = [inf, rel, mot, ori];
  const finalValue = allVals.reduce(getFinalValue, { img: '', char: '' });

  return finalValue;
}

function getFinalValue(prev, current) {
  const img = prev.img + current.img;
  const char = prev.char + ' ' + current.char;
  return { img, char };
}

function gague(param, high, low) {
  if (param >= 3) return { char: high, img: 'H' };
  return { char: low, img: 'L' };
}

let result = getRadioParameters(3, 3, 3, 3);
console.log(result);

result = getRadioParameters(3, 3, 3, 0);
console.log(result);

result = getRadioParameters(3, 3, 0, 3);
console.log(result);

result = getRadioParameters(3, 0, 3, 3);
console.log(result);

答案 2 :(得分:0)

如果我了解您要正确做的事,我想您可以做类似的事情

    var obj = {
        "highInfluence_highRelevance": highInfluenceHighRelevance,
        "highInfluence_lowRelevance": highInfluenceLowRelevance,
        "lowInfluence_highRelevance": lowInfluenceHighRelevance,
        "lowInfluence_lowRelevance": lowInfluenceLowRelevance,
        "highMotivation_highOrientation": highMotivationHighOrientation,
        "highMotivation_lowOrientation": highMotivationLowOrientation,
        "lowMotivation_highOrientation": lowMotivationHighOrientation,
        "lowMotivation_lowOrientation": lowMotivationLowOrientation
    }

    var imgStr = "";

    function evaluateRadioParameters(num) {
        if (num >= 3) return "high";
        else if (num < 3) return "low";
        return "";
    }

    function setimgStr(num, str) {
        if (num >= 3) imgStr += "H";
        else if (num < 3) imgStr += "L";
       else console.log('problem with ' + str + '. It is = ', num);
    }

    function getRadioParameters(influence, relevance, motivation, orientation) {
        var influenceStr = evaluateRadioParameters(influence);
        var relevanceStr = evaluateRadioParameters(relevance);
        var motivationStr = evaluateRadioParameters(motivation);
        var orientationStr = evaluateRadioParameters(orientation);

        if (influenceStr == "" || relevanceStr == "") {
            influenceRelevanceArr.push("");
        } else {
            influenceRelevanceArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (motivationStr == "" || orientationStr == "") {
            motivationOrientationArr.push("");
        } else {
            motivationOrientationArr.push(obj[influenceStr + "Influence_" + relevanceStr + "Relevance"]);
        }

        if (influenceStr == "" || relevanceStr == "" || motivationStr == "" || orientationStr == "")
            stkImagesArr.push('');
        else {
            setimgStr(influence, "influence");
            setimgStr(relevance, "relevance");
            setimgStr(motivation, "motivation");
            setimgStr(orientation, "orientation");
            stkImagesArr.push(getImage(imgStr));
        }

    }