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


当前回答

带有函数的Wrapp

(function(){
alert('start')

return;
alert('no exec')
})

其他回答

要停止脚本执行而不出现任何错误,可以将所有脚本包含到函数中并执行它。 这里有一个例子: (函数(){ console.log(一); 返回; console.log(两个); }) ();

上面的脚本将只记录一个日志。

在使用前

如果您需要在脚本本身之外读取脚本的函数,请记住(通常)这是行不通的:要做到这一点,您需要使用一个预先存在的变量或对象(您可以将函数放在窗口对象中)。 上面的代码可能是你不想要的:将整个脚本放在一个函数中可能会产生其他后果(例如,这样做,脚本将立即运行,并且没有办法从浏览器开发中修改其部分,正如我所知道的,在Chrome中)

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()函数基本上实现了我的第二段,即它只是抛出一个错误。

"exit"函数通常退出程序或脚本,并以错误消息作为参数。例如php中的die(…)

die("sorry my fault, didn't mean to but now I am in byte nirvana")

在JS中等效的是用throw关键字发出错误信号,如下所示:

throw new Error();

你可以很容易地测试这个:

var m = 100;
throw '';
var x = 100;

x
>>>undefined
m
>>>100

在JavaScript中有多种方式,下面是其中的一些

方法1:

throw new Error("Something went badly wrong!");

方法2:

return;

方法3:

return false;

方法4:

new new

方法5:

使用上述方法编写自定义函数,并在需要的地方调用

注意: 如果您想暂停代码执行,您可以使用

debugger; 

带有函数的Wrapp

(function(){
alert('start')

return;
alert('no exec')
})