满足特定条件时停止 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3536055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stopping a JavaScript function when a certain condition is met
提问by Rhys
I can't find a recommended way to stop a function part way when a given condition is met. Should I use something like exitor break?
我找不到在满足给定条件时中途停止功能的推荐方法。我应该使用类似exit或 的东西break吗?
I am currently using this:
我目前正在使用这个:
if ( x >= 10 ) { return; }
// other conditions;
回答by g.d.d.c
Return is how you exit out of a function body. You are using the correct approach.
Return 是退出函数体的方式。您正在使用正确的方法。
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.
我想,根据您的应用程序的结构,您也可以使用 throw。这通常要求您对函数的调用包含在 try / catch 块中。
回答by Starx
use returnfor this
return为此使用
if(i==1) {
return; //stop the execution of function
}
//keep on going
回答by Timwi
The returnstatement exits a function from anywhere within the function:
该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!");
}
回答by Rahul Munjal
Use a try...catchstatement in your main function and whenever you want to stop the function just use:
try...catch在您的主函数中使用语句,无论何时您想停止该函数,只需使用:
throw new Error("Stopping the function!");
回答by Spidy
Try using a return statement. It works best. It stops the function when the condition is met.
尝试使用 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);
}

