Use while loop

In JavaScript there, in general we want the program to perform a half, after the judgment or take some action to stop the implementation of the code behind will end with a return off function in function inside.

fuction(){
    //do something...
    if(stopRun == true){
        return
    }
    //continue do ...
}

But if I do judge a multi-layer, but also to judge interrupted just a code behind it?

function(){
    //代码1... if(stopRun == true){ //代码2 ... if(cando == false){ return } //代码3 ... } //代码4 ... }

As the above logic, cando judge just want to stop the implementation of 'Code 3', and 'Code 4' I need, but return operation has been the end of the whole function off.
Then the following focus here, while break the magical effect can be achieved interrupt code, rather than the end of the entire function.

var stopRun = true,cando = false; function ww(){ //代码1... while(stopRun == true){ //代码2 ... console.log(2) if(cando == false){ break } //代码3 ... console.log(3) break } //代码4 ... console.log(4)

3 prove that the code is blocked, but did not prevent the execution of function code behind.

break can not be used if the inside, but you can use inside the loop, so use this while loop can interrupt the execution of the code, in theory, all cycles can achieve this function, select while because it is simple and can be replaced if to make a judgment.
!!! attention !!! while last remember to add a break, otherwise it will turn into an endless loop.

May be added if a plurality of intermediate while () break as a breakpoint, the flow control logic.

function(){
    var a=0; while(a==0){ console.log("A") a++ if(a!=1)break console.log("B") a++ if(a!=2)break console.log("C") break } }
 
 Copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/wjybk/p/11873454.html