当满足给定条件时,我找不到推荐的方法来部分停止函数。我应该使用类似exit
or的东西break
吗?
我目前正在使用这个:
if ( x >= 10 ) { return; }
// other conditions;
当满足给定条件时,我找不到推荐的方法来部分停止函数。我应该使用类似exit
or的东西break
吗?
我目前正在使用这个:
if ( x >= 10 ) { return; }
// other conditions;
Return 是退出函数体的方式。您正在使用正确的方法。
我想,根据您的应用程序的结构,您也可以使用 throw。这通常要求您对函数的调用包含在 try / catch 块中。
用于return
此
if(i==1) {
return; //stop the execution of function
}
//keep on going
该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!");
}
在你的主函数中使用一个try...catch
语句,每当你想停止函数时,只需使用:
throw new Error("Stopping the function!");
尝试使用 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);
}
if (OK === guestList[3]) {
alert("Welcome");
script.stop;
}