我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。


当前回答

我想这个问题已经有答案了,点击这里了解更多信息。下面是它发布的简短答案。

throw new Error("Stop script");

您也可以使用您的浏览器添加断点,每个浏览器都是类似的,检查以下信息为您的浏览器。

为Chrome断点信息点击这里 有关Firefox断点信息,请点击这里 有关资源管理器断点信息,请单击 有关Safari断点信息,请点击这里

其他回答

If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.

注意,在实践中,大多数浏览器的Javascript解释器在遇到错误时会简单地停止运行当前脚本。所以你可以做一些事情,比如访问一个未设置变量的属性:

function exit() {
    p.blah();
}

它可能会中止脚本。但你不应该指望它,因为它根本不是标准的,而且它看起来真的是一个糟糕的做法。

编辑:好吧,也许这不是一个很好的答案Ólafur的光。尽管他链接到的die()函数基本上实现了我的第二段,即它只是抛出一个错误。

我使用ibroker和容易地设法停止脚本

stopScript();

我使用这段代码来停止执行:

throw new FatalError("!! Stop JS !!");

虽然你会得到一个控制台错误,但这对我来说很好。

这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

退出JS或Node脚本的方法有很多。以下是最相关的:

// This will never exit!
setInterval((function() {  
    return;
}), 5000);

// This will exit after 5 seconds, with signal 1
setTimeout((function() {  
    return process.exit(1);
}), 5000);

// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {  
    return process.kill(process.pid);
}), 5000);

// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {  
    return process.abort();
}), 5000);

如果你在REPL中(即在命令行上运行node之后),你可以输入.exit退出。