我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
当前回答
我不喜欢回答那些不是真正解决方案的问题……
...但当我遇到同样的问题时,我采取了以下解决方案:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
希望对大家有用。
其他回答
退出();可以用来进行下一次验证。
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
显然你可以这样做:
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
如果你正在使用jquery。这将阻止函数冒泡到,因此父函数调用它也应该停止。
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
我认为抛出一个新的错误是停止执行的好方法,而不是仅仅返回或返回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才有效,否则不起作用。