2015-12-24 95 views
-1

是否可能从函数中断执行程序或者我需要检查boolean val返回?从函数中断执行

代码

function check(something) { 

    if (!something) return; 
    // Else pass and program continuing 
} 

check(false); // I want to stop execution because function has returned 
// Or I need to check value like if (!check(false)) return; ? 
// I want easiest possible without re-check value of function.. 

alert("hello"); 
+0

办法阻止从函数执行,而无需重新检查其返回值... – Davide

+3

您只能'return'如果您'在一个函数中。从顶级脚本代码无法做到这一点。 – Barmar

+0

@Barmar [除非你使用Node.js](http://stackoverflow.com/q/28955047/1903116):D – thefourtheye

回答

1

一种方法是要通过错误,但在其他方面,你需要使用一个布尔检查,是的。我会建议使用布尔

function check(something) { 
 

 
    if (!something) throw ""; 
 
    // Else pass and program continuing 
 
} 
 

 
check(false); // I want to stop execution because function has returned 
 
// Or I need to check value like if (!check(false)) return; ? 
 
// I want easiest possible without re-check value of function.. 
 

 
alert("hello");

0

最简单的...

(function(){ 
    function check(something) { 

    if (!something) return false; 
    // Else pass and program continuing 
    } 

    if(!check(false)) return; 

    alert("hello"); 
}); 

(function(){ ... });被称为IIFE立即调用的函数表达式。

0

放在一个IIFE你的代码,那么你可以使用return

(function() { 
    function check(something) { 
     if (!something) { 
      return false; 
     } else { 
      return true; 
     } 
    } 

    if (!check(false)) { 
     return; 
    } 

    alert("hello"); 
});