关于if函数中的if语句的问题 - 如果if语句返回true但函数返回false

dra*_*sea 4 javascript function

我可以问你们一个问题吗?以下是我的代码:

var num = 1;
var isNumberEqualOne = function(){
    if(num == 1){
      return true;
    }
    return false;
}();
alert(isNumberEqualOne);
Run Code Online (Sandbox Code Playgroud)

在这段代码中,函数中的语句返回true,返回true后,函数中的代码仍在执行吗?所以最后,代码满足返回false,所以为什么函数仍然返回true.Sorry for my bad english.Thanks

T.J*_*der 7

正如alex所说,该return函数立即将控制转移出函数调用; finally执行函数(块除外)中没有其他语句.

所以:

function foo(a) {
    if (a == 1) {
        alert("a is 1");
        return;
        alert("This never happens, it's 'dead code'");
    }
    alert("a is not 1");
}
foo(1); // alerts "a is 1" and nothing else
foo(2); // alerts "a is not 1"
Run Code Online (Sandbox Code Playgroud)

关于我上面所说的"函数中没有其他语句(finally块除了) ",更多关于finally块:

function foo(a) {
    try {
        if (a == 3) {
            throw "a is e";
        }
        if (a == 1) {
            alert("a is 1");
            return;
            alert("This never happens, it's 'dead code'");
        }
        alert("a is not 1");
    }
    catch (e) {
        alert("exception: " + e);
    }
    finally {
        alert("finally!");
    }
}
foo(1); // alerts "a is 1", then "finally!"
foo(2); // alerts "a is not 1", then "finally!"
foo(3); // alerts "exception: a is 3", then "finally!"
Run Code Online (Sandbox Code Playgroud)

请注意,无论执行如何离开try/catch块,无论是自然地从底部掉落return,还是因为异常而提前或早期,finally块中的代码总是运行.


偏离主题:另外,请注意,如果您要立即调用它,则需要围绕该函数表达式使用括​​号:

    var isNumberEqualOne = (function(){
//                         ^--- here
        if(num == 1){
           return true;
        }
        return false;
    })();
//   ^--- and here
Run Code Online (Sandbox Code Playgroud)

或者你可以把()它称之为这样的parens:

    var isNumberEqualOne = (function(){
//                         ^--- here
        if(num == 1){
           return true;
        }
        return false;
    }());
//     ^--- and here
Run Code Online (Sandbox Code Playgroud)

要么有效.


ale*_*lex 6

return将停止该功能并立即返回.函数中剩余的代码体将不会被执行.

在您的示例中,num已分配1,因此函数内的条件为true.这意味着你的函数将返回那里,然后返回true.

您也可以重写该功能,以便它的正文return (num == 1).