我有一个函数:
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()的东西?
当前回答
使用return将停止函数并返回未定义的值,或者返回使用return命令指定的值。
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}
其他回答
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
退出();可以用来进行下一次验证。
我认为抛出一个新的错误是停止执行的好方法,而不是仅仅返回或返回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才有效,否则不起作用。
输入任何抛出错误的随机命令,例如:
exit
or
die:-)
这样的:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}