简体   繁体   中英

Loop in JavaScript until a condition is met

I'm trying to loop indefinitely until a condition is met...is the following correct?

It seems not to be.

    var set = false;
    while(set !== true) {
        var check = searchArray(checkResult, number);
        if(check === false) {
            grid.push(number);
            set = true;
        } 
    }

Basically, you can make an infinite loop with this pattern and add a break condition anywhere in the loop with the statement break :

while (true) {
    // ...
    if (breakCondition) {            
        break;
    } 
}

The code will loop while searchArray result is not false and until it becomes false . So the code is correct if you wanted to achieve such behavior and it's not correct otherwise.

Let's go over this. You want the code to loop until the function searcharray() returns true, right?

First, the code creates the variable "set" and sets it to false.

Then while set is not equal to true (would suggest using triple equals here), run this code:

Create the variable "check" and set it to what searcharray returns.

If searcharray returns false, it will add a number on to the end of the array grid as a new entry and then set "set" to true.

Then it loops again. If searcharray returned true, it loops again as set is still false. If search array returned false, it does not loop again and skips to the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM