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


当前回答

简单地创建一个BOOL条件, 这里不需要复杂的代码。

即使你把它变成true/或多次, 它会给你一条解,而不是多条解 基本上就是这么简单。

其他回答

退出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退出。

在JavaScript中有多种方式,下面是其中的一些

方法1:

throw new Error("Something went badly wrong!");

方法2:

return;

方法3:

return false;

方法4:

new new

方法5:

使用上述方法编写自定义函数,并在需要的地方调用

注意: 如果您想暂停代码执行,您可以使用

debugger; 

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 '';
}

把“”;

是对这个概念的误用,但可能是唯一的选择。是的,您必须重置所有事件侦听器,就像接受的答案提到的那样。如果我是对的,你还需要一个单一的入口。

在它的顶部:你想要一个通过电子邮件向你报告的页面,你可以使用例如Raven/Sentry。但这意味着,你给自己制造了假阳性。在这种情况下,您还需要更新默认处理程序以过滤掉此类事件,或者在Sentry的仪表板上将此类事件设置为忽略。

window.stop ();

这在页面加载期间不起作用。它也会停止对页面的解码。所以你不能用它来为用户提供网页的无javascript变体。

调试器;

仅在调试器打开时停止执行。工作很好,但不能交付。

简单地创建一个BOOL条件, 这里不需要复杂的代码。

即使你把它变成true/或多次, 它会给你一条解,而不是多条解 基本上就是这么简单。