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


当前回答

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

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

其他回答

这是一个例子, 如果条件存在,则终止脚本。 我使用这个在我的SSE客户端javascript,如果

<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>

不能直接从JSON解析…

if( ! SSE_HOST  ) throw new Error(['[!] SSE.js: ERR_NOHOST - finished !']);

... 总之,总的思想是:

if( error==true) throw new Error([ 'You have This error' ,  'At this file', 'At this line'  ]);

这将终止/死亡你的javascript脚本

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

方法1:

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

方法2:

return;

方法3:

return false;

方法4:

new new

方法5:

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

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

debugger; 

我知道这是旧的,但如果你想要一个类似的PHP die()函数,你可以这样做:

function die(reason) {
    throw new Error(reason);
}

用法:

console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");

上面的例子只打印“Hello”。

即使在没有句柄、事件等的简单程序中,最好将代码放在主函数中,即使它是唯一的过程:

<script> 
function main()
{
//code

}
main();
</script>

这样,当你想要停止程序时,你可以使用return。

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

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