2015-12-24 92 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"); 
});