我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
"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
其他回答
这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。
function exit(Msg)
{
Msg=Msg?'*** '+Msg:'';
if (Msg) alert(Msg);
throw new Error();
} // exit
我想这个问题已经有答案了,点击这里了解更多信息。下面是它发布的简短答案。
throw new Error("Stop script");
您也可以使用您的浏览器添加断点,每个浏览器都是类似的,检查以下信息为您的浏览器。
为Chrome断点信息点击这里 有关Firefox断点信息,请点击这里 有关资源管理器断点信息,请单击 有关Safari断点信息,请点击这里
这段代码将停止当前窗口中所有javascript的执行:
(,);
例子
console.log('READY!'); setTimeout(()=>{ /* animation call */ div.className = "anim"; console.log('SET!'); setTimeout(()=>{ setTimeout(()=>{ console.log('this code will never be executed'); },1000); console.log('GO!'); /* BOMB */ for(;;); console.log('this code will never be executed'); },1000); },1000); #div { position: fixed; height: 1rem; width: 1rem; left: 0rem; top: 0rem; transition: all 5s; background: red; } /* this <div> will never reached the right bottom corner */ #div.anim { left: calc(100vw - 1rem); top: calc(100vh - 1rem); } <div id="div"></div>
这是一个例子, 如果条件存在,则终止脚本。 我使用这个在我的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脚本
在大多数情况下不适用,但我有很多异步脚本在浏览器中运行,作为一个hack我做
window.reload();
停止一切。