78

当满足给定条件时,我找不到推荐的方法来部分停止函数。我应该使用类似exitor的东西break吗?

我目前正在使用这个:

if ( x >= 10 ) { return; }  
// other conditions;
4

6 回答 6

94

Return 是退出函数体的方式。您正在使用正确的方法。

我想,根据您的应用程序的结构,您也可以使用 throw。这通常要求您对函数的调用包含在 try / catch 块中。

于 2010-08-21T02:53:41.450 回答
36

用于return

if(i==1) { 
    return; //stop the execution of function
}

//keep on going
于 2010-08-21T02:54:33.973 回答
13

return语句从函数内的任何位置退出函数:

function something(x)
{
    if (x >= 10)
        // this leaves the function if x is at least 10.
        return;

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");
}
于 2010-08-21T02:54:00.653 回答
9

在你的主函数中使用一个try...catch语句,每当你想停止函数时,只需使用:

throw new Error("Stopping the function!");
于 2016-02-16T07:52:08.853 回答
0

尝试使用 return 语句。它效果最好。满足条件时停止函数。

function anything() {
    var get = document.getElementsByClassName("text ").value;
    if (get == null) {
        alert("Please put in your name");
    }

    return;

    var random = Math.floor(Math.random() * 100) + 1;
    console.log(random);
}
于 2019-04-23T11:33:33.690 回答
0
if (OK === guestList[3]) {
    alert("Welcome");
    script.stop;
}
于 2021-12-10T13:29:54.687 回答