2010-08-21 133 views

回答

56

回报是你如何退出函数体了。您正在使用正确的方法。

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

+0

感谢您的确认。 Google搜索找不到此答案。 – Rhys 2010-08-21 03:08:38

+0

真的吗?只是抛出异常退出函数?不好的建议...... – WoIIe 2014-07-29 11:59:51

+5

@Wolle - 你会注意到我都将它列为_alternative_,并且要求函数的调用需要包含在try/catch块中。根据函数,项目范围和函数完成的功能,引发异常退出可能是非常合适的。没有深入了解OP的实施情况,人们无法知晓。无论哪种方式,我的答案是使用'return',而不是'throw'。 – 2014-07-29 14:43:54

7

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

使用return

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

//keep on going 
+1

如果您期待布尔返回并在其他情况下返回true,则仅返回false才有意义。他可能会返回一个数组值,或状态指示符,或提示他作为条件结果的功能有多远。 – 2010-08-21 02:59:10

+1

你是对的..... – Starx 2010-08-21 03:13:05

1

在主函数使用try...catch声明,只要你想停止功能只是使用:

throw new Error("Stopping the function!"); 
相关问题