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


当前回答

如果你在脚本中使用任何未定义的函数,那么脚本将由于“Uncaught ReferenceError”而停止。我已经尝试了以下代码和执行的前两行。

我认为,这是停止剧本的最好方法。如果有任何其他方式,请评论我。我还想知道另一种最好最简单的方法。BTW,我没有得到退出或死亡内置函数在Javascript像PHP终止脚本。如果有人知道,请告诉我。

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

其他回答

如果你不关心它是一个错误,可以这样写:

fail;

这将阻止您的主(全局)代码继续进行。 对调试/测试的某些方面很有用。

这是一个例子, 如果条件存在,则终止脚本。 我使用这个在我的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的执行:

(,);

例子

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>

"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