如何退出 JavaScript 脚本,就像 PHPexit
或die
? 我知道这不是最好的编程实践,但我需要这样做。
如何在 JavaScript 中终止脚本?
IT技术
javascript
exit
die
2021-01-16 05:34:51
6个回答
“退出”函数通常会退出程序或脚本,并带有错误消息作为参数。例如 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
JavaScript 相当于 PHP 的die
. 顺便说一句,它只是调用exit()
(感谢 splattne):
function exit( status ) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brettz9.blogspot.com)
// + input by: Paul
// + bugfixed by: Hyam Singer (http://www.impact-computing.com/)
// + improved by: Philip Peterson
// + bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
// % note 1: Should be considered expirimental. Please comment on this function.
// * example 1: exit();
// * returns 1: null
var i;
if (typeof status === 'string') {
alert(status);
}
window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);
var handlers = [
'copy', 'cut', 'paste',
'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
];
function stopPropagation (e) {
e.stopPropagation();
// e.preventDefault(); // Stop for the form controls, etc., too?
}
for (i=0; i < handlers.length; i++) {
window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
}
if (window.stop) {
window.stop();
}
throw '';
}
即使在没有句柄、事件等的简单程序中,最好将代码放在“主”函数中,即使它是唯一的过程:
<script>
function main()
{
//code
}
main();
</script>
这样,当您想停止程序时,您可以使用“返回”。
如果你不在乎这是一个错误,只需写:
fail;
这将阻止您的主要(全局)代码继续进行。对调试/测试的某些方面很有用。
有很多方法可以退出 JS 或 Node 脚本。以下是最相关的:
// This will never exit!
setInterval((function() {
return;
}), 5000);
// This will exit after 5 seconds, with signal 1
setTimeout((function() {
return process.exit(1);
}), 5000);
// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {
return process.kill(process.pid);
}), 5000);
// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {
return process.abort();
}), 5000);
如果您在REPL 中(即在node
命令行上运行后),您可以键入.exit
退出。