我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
简单地创建一个BOOL条件, 这里不需要复杂的代码。
即使你把它变成true/或多次, 它会给你一条解,而不是多条解 基本上就是这么简单。
其他回答
如果你在脚本中使用任何未定义的函数,那么脚本将由于“Uncaught ReferenceError”而停止。我已经尝试了以下代码和执行的前两行。
我认为,这是停止剧本的最好方法。如果有任何其他方式,请评论我。我还想知道另一种最好最简单的方法。BTW,我没有得到退出或死亡内置函数在Javascript像PHP终止脚本。如果有人知道,请告诉我。
alert('Hello');
document.write('Hello User!!!');
die(); //Uncaught ReferenceError: die is not defined
alert('bye');
document.write('Bye User!!!');
我使用return语句而不是throw,因为throw在控制台给出错误。最好的办法是检查情况
if(condition){
return //whatever you want to return
}
这只是从这一行停止程序的执行,而不是在控制台中给出任何错误。
这段代码将停止当前窗口中所有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脚本
如果你只是想停止执行更多的代码而不“抛出”任何错误,你可以暂时覆盖window。如cross-exit所示:
function exit(code) {
const prevOnError = window.onerror
window.onerror = () => {
window.onerror = prevOnError
return true
}
throw new Error(`Script termination with code ${code || 0}.`)
}
console.log("This message is logged.");
exit();
console.log("This message isn't logged.");
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?