【问题标题】:Converting if-else statement to if-else if-else statement将 if-else 语句转换为 if-else if-else 语句
【发布时间】:2023-08-19 09:01:01
【问题描述】:

如何将此嵌套的if-else 语句转换为非嵌套的if-else if-else 语句?您可能需要添加一些布尔运算符以使其完全非嵌套:

if (ball > 0) {
    if (cup > 0) {
        console.log(“I have a ball and cup.”);
    } else {
        console.log(“I have a ball.”);
    }
} else {
    if (cup > 0) {
        console.log(“I have a cup”);
    } else {
        console.log(“I have nothing”);
    }
}

【问题讨论】:

    标签: if-statement nested boolean


    【解决方案1】:

    如果我理解你想要做什么,那么也许这会有所帮助:

    if (ball > 0 && cup > 0) {
        console.log(“I have a ball and cup.”);
    } else if (ball > 0) {
        console.log(“I have a ball.”);
    }
    if (ball <= 0 && cup > 0) {
        console.log(“I have a cup”);
    } else if (ball <= 0) {
        console.log(“I have nothing”);
    }
    

    您可以只检查每个if 语句中的多个条件,而不是嵌套if-else 语句。

    【讨论】: