Stopping a JavaScript function when a certain condition is met

让人想犯罪 __ 提交于 2019-11-28 18:11:41

问题


I can't find a recommended way to stop a function part way when a given condition is met. Should I use something like exit or break?

I am currently using this:

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

回答1:


Return is how you exit out of a function body. You are using the correct approach.

I suppose, depending on how your application is structured, you could also use throw. That would typically require that your calls to your function are wrapped in a try / catch block.




回答2:


use return for this

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

//keep on going



回答3:


The return statement exits a function from anywhere within the function:

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!");
}



回答4:


Use a try...catch statement in your main function and whenever you want to stop the function just use:

throw new Error("Stopping the function!");



回答5:


Try using a return statement. It works best. It stops the function when the condition is met.

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);
}


来源:https://stackoverflow.com/questions/3536055/stopping-a-javascript-function-when-a-certain-condition-is-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!