我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。
当前回答
我使用return语句而不是throw,因为throw在控制台给出错误。最好的办法是检查情况
if(condition){
return //whatever you want to return
}
这只是从这一行停止程序的执行,而不是在控制台中给出任何错误。
其他回答
如果你在脚本中使用任何未定义的函数,那么脚本将由于“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;
这将阻止您的主(全局)代码继续进行。 对调试/测试的某些方面很有用。
我使用这段代码来停止执行:
throw new FatalError("!! Stop JS !!");
虽然你会得到一个控制台错误,但这对我来说很好。
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()函数基本上实现了我的第二段,即它只是抛出一个错误。
我知道这是旧的,但如果你想要一个类似的PHP die()函数,你可以这样做:
function die(reason) {
throw new Error(reason);
}
用法:
console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");
上面的例子只打印“Hello”。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?