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


当前回答

我使用return语句而不是throw,因为throw在控制台给出错误。最好的办法是检查情况

if(condition){
 return //whatever you want to return
}

这只是从这一行停止程序的执行,而不是在控制台中给出任何错误。

其他回答

即使在没有句柄、事件等的简单程序中,最好将代码放在主函数中,即使它是唯一的过程:

<script> 
function main()
{
//code

}
main();
</script>

这样,当你想要停止程序时,你可以使用return。

"exit"函数通常退出程序或脚本,并以错误消息作为参数。例如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

这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

Javascript可以在devtools中禁用:ctrl+shift+j跟随cltf+shift+p,然后输入disable Javascript

上述可能的选项:

window.stop(); // equivalent to the 'stop' button in the browser
debugger; // debugs
for(;;); // crashes your browser
window.location.reload(); // reloads current page

如果页面已加载,而你不想调试崩溃或重新加载:

throw new Error();

此外,清除所有超时

var id = window.setTimeout(function() {}, 0);
while (id--) {
    window.clearTimeout(id);
}

中止DOM - XMLHttpRequest

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(i, jqXHR) { 
        jqXHR.abort();  
        $.xhrPool.splice(i, 1); 
    });
}
$.ajaxSetup({
    beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR);
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

删除所有事件监听器,包括内联监听器

$("*").prop("onclick", null).off();

这将删除脚本并重新创建没有事件的元素

$('script').remove();
$('*').each(function(){
    $(this).replaceWith($(this).clone());   
});

如果网页上没有jQuery,则复制粘贴源代码到控制台。

可能还有其他的东西。请在评论中告诉我。

我使用这段代码来停止执行:

throw new FatalError("!! Stop JS !!");

虽然你会得到一个控制台错误,但这对我来说很好。