我有一个函数:

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

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


当前回答

输入任何抛出错误的随机命令,例如:

exit

or

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()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

我认为抛出一个新的错误是停止执行的好方法,而不是仅仅返回或返回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才有效,否则不起作用。

如果你正在使用jquery。这将阻止函数冒泡到,因此父函数调用它也应该停止。

  function myfunction(e)
  {
       e.stopImmediatePropagation();
       ................
  }
function myfunction() {
     if(a == 'stop') 
         return false;
}

返回错误;比只是回报要好得多;