我需要一个能退出js脚本的代码,就像PHP'exit'或'die'一样.(我知道它不是最好的编程实践,但我需要它).
PHP的等价物die
.BTW它只是打电话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 ''; }
"exit"函数通常退出程序或脚本以及错误消息作为参数.例如在php中死(...)
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
即使在没有句柄,事件等的简单程序中,最好将代码放在"main"函数中,即使它是唯一的过程:
这样,当您想要停止程序时,您可以使用"返回".
有许多方法可以退出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
退出.
如果您不在乎这是一个错误,请输入:
fail;
这将阻止您的主要(全局)代码继续进行。对于调试/测试的某些方面很有用。