开发者

How do I terminate Javascript execution, á la exit/die/fatal assertion, etc.?

I have a loop in Javascript, I want to run console.log() in a specific iteration, and then terminate. What is the best meth开发者_开发技巧od to go about doing this?

I'm wanting something like Perl's

die Dumper \@foo;


You can throw an exception:

throw "Help I have fallen and cannot get up";

Not exactly the same, but (in my experience) it's not too common to see exception handling in ordinary DOM-wrangling sorts of JavaScript code, so that usually will blow out of any event loop. However, it's not really the same thing as any surroundling try block will catch what you throw.


you mean terminate loop?

while(true) {
console.log()
if(condition) {break};
}

the break command exits the loop

but there is no kill or exit function in javascript.


Since JavaScript is event-based, a script doesn't control when it terminates — there's no die or exit.

If it's not one already, the best option is to refactor the code into a function that you can return from, or use a named block:

foo: {
    // do work
    break foo;
    // not executed;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜