首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免多个嵌套的if语句

避免多个嵌套的if语句
EN

Stack Overflow用户
提问于 2018-08-17 21:52:39
回答 3查看 74关注 0票数 0

我正在写一个函数,它根据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语句,还是其他什么?

下面是整个函数:

代码语言:javascript
复制
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);
        }
    }

}

谢谢!

EN

回答 3

Stack Overflow用户

发布于 2018-08-17 22:04:16

下面是一个使用函数将其抽象出来的示例:

代码语言:javascript
复制
//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));

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

深度嵌套代码增加了推理的难度,这不仅会降低代码的可维护性,还会增加引入bug的机会。即使有bug,也很难调试深度嵌套的代码。

希望这能对你有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2018-08-17 22:20:01

单独获取每个单独的值,然后以某种方式组合它们可能会更容易-这完全取决于您的数据结构。到目前为止,我认为你可以这样做(这是高级的,你必须自己填写完整的细节):

代码语言:javascript
复制
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,则可以进一步简化代码:

代码语言:javascript
复制
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);

票数 0
EN

Stack Overflow用户

发布于 2018-08-17 23:22:32

如果我理解你想要做什么,我认为你可以这样做

代码语言:javascript
复制
    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));
        }

    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51896916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档