首页 > 解决方案 > 返回 IF ELSE IF 语句的函数

问题描述

我正在尝试运行一段代码,它是一系列 IF ELSE IF 语句,用于检查某些条件是否为真。

    if (2 > 1) {
        return true;
    }

    else if (3 > 1) {
        return true;
    }

    else if (4 > 1) {
        return true;
    }

    else {
        alert('Not all conditions are true')
    }

它工作正常,但我想在最后添加一个函数,如果所有条件都为真,在下面的代码中我添加了该函数,但现在似乎在没有先检查所有条件的情况下运行该函数

    if (2 > 1) {
        return true;
    }
    else if (3 > 1) {
        return true;
    }
    else if (4 > 1) {
        return true;
    }
    else {
        alert('Not all conditions are true')
    }

    // Run this function after checking all the conditions are true
    allConditionsTrue();

我想我对应该放置函数的位置感到困惑。

任何帮助是极大的赞赏 :)

标签: javascriptif-statement

解决方案


对于任意计数的条件并且如果前一个条件是false并且下一个条件是立即退出true,您可以在someFalse值出现时为状态取一个变量。

Afetr 检查所有条件检查someFalse并返回'Not all conditions are true'

最后很明显,所有条件都是true,您可以为这种情况调用函数。

function check(value) {
    function allConditionsTrue() {
        console.log('All conditions are true');
    }
    
    let someFalse = false,
        conditions = [value < 2, value < 3, value < 4],
        fn = c => c ? someFalse : !(someFalse = true);

    if (conditions.some(fn)) return true;

    if (someFalse) {
        console.log('Not all conditions are true');
        return false;
    }
    
    allConditionsTrue();
    return true;
}

console.log(1, check(1));
console.log(2, check(2));
console.log(3, check(3));
console.log(4, check(4));


推荐阅读