我有一个函数:

function myfunction() {
  if (a == 'stop')  // How can I stop the function here?
}

JavaScript中是否有类似exit()的东西?


当前回答

显然你可以这样做:

function myFunction() {myFunction:{
    console.log('i get executed');
    break myFunction;
    console.log('i do not get executed');
}}

通过使用标签查看块作用域:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

我还看不出有什么不好。但这似乎不是一种常用的用法。

推导出这个答案:JavaScript等价于PHP的die

其他回答

你可以用return。

function myfunction() {
     if(a == 'stop') 
         return;
}

这将向调用函数的对象发送一个undefined的返回值。

var x = myfunction();

console.log( x );  // console shows undefined

当然,您可以指定不同的返回值。无论返回的值是什么,都将使用上面的示例记录到控制台。

return false;
return true;
return "some string";
return 12345;

显然你可以这样做:

function myFunction() {myFunction:{
    console.log('i get executed');
    break myFunction;
    console.log('i do not get executed');
}}

通过使用标签查看块作用域:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

我还看不出有什么不好。但这似乎不是一种常用的用法。

推导出这个答案:JavaScript等价于PHP的die

我认为抛出一个新的错误是停止执行的好方法,而不是仅仅返回或返回false。例如,我正在验证一些文件,我只允许在单独的功能上传最多5个文件。

validateMaxNumber: function(length) {
   if (5 >= length) {
        // Continue execution
   }
   // Flash error message and stop execution
   // Can't stop execution by return or return false statement; 
   let message = "No more than " + this.maxNumber + " File is allowed";
   throw new Error(message);
}

但是我把这个函数从主流函数中调用为

  handleFilesUpload() {
      let files =  document.getElementById("myFile").files;
      this.validateMaxNumber(files.length);
}

在上面的例子中,除非抛出new Error,否则我无法停止执行。只有当你在执行main函数时,return或return false才有效,否则不起作用。

使用return将停止函数并返回未定义的值,或者返回使用return命令指定的值。

function myfunction(){
    if(a=="stop"){
        //return undefined;
        return; /** Or return "Hello" or any other value */
    }
}

退出();可以用来进行下一次验证。