终止Javascript,无错误/异常 [英] Terminate Javascript without error / exception

查看:74
本文介绍了终止Javascript,无错误/异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要终止一个函数的javascript,以便它不执行下一个代码块以及该脚本所调用的其他函数(紧随当前函数之后).

I need to terminate the javascript from a function so that it doesn't execute the next block of codes and other functions called by the script, which follows the current function.

我在SO中发现了这个现有问题:如何终止Javascript中的脚本,其中给出了触发错误/异常的解决方案,该错误/异常将立即终止脚本.

I found this existing question in SO : How to terminate the script in Javascript , where the solution is given as to trigger an error / exception which will terminate the script immediately.

但是我的情况有所不同,因为,终止当前脚本的目的是为了防止由于当前函数没有停止执行脚本而导致下一个函数产生错误.因此,触发另一个错误以防止错误并不能解决我的目的!

But my case is different because, My purpose of terminating the script is to prevent an error which will come from the next functions, if the current function doesn't stop execution of the script. So, triggering another error to prevent an error is no way solving my purpose!

那么,还有其他方法可以终止javascript而不是抛出错误/异常吗?

So, is there any other way of terminating the javascript instead of throwing an error / exception?

在标记为重复项之前,请先仔细阅读我的问题,我已经解释了为什么我提出的问题不能解决我的问题!.

推荐答案

由于您位于函数内部,因此只需

Since you're inside a function, just return.

多读一点您的问题,即它不执行脚本调用的其他函数",您应该返回一个布尔值.例如,如果您不希望调用其余的语句,则返回false,然后将其余的语句包装在if中:

Reading into your question a little more that it doesn't execute "other functions called by the script", you should return a boolean. For example, return false if you don't want the rest called, then wrap the remaining statements in an if:

function Foo() {
    if (weAreInLotsOfTrouble) {
        return false;
    }

    return true;
}

DoSomething();
DoSomethingElse();

if (Foo()) {
    DoSomethingDangerous();
}

这篇关于终止Javascript,无错误/异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆