如果条件满足,如何退出while循环

时间:2019-07-24 09:59:12

标签: javascript while-loop

如果条件为true,则退出while循环,但是我的while循环在尝试另一个循环后退出。

let moveNavigation = 0;
            let currentItemFocus;
                let jsonString;
                let hasMovedList= false;

            currentItemFocus = yield page.getFocusedNode();
                    while (!hasMovedList) {
                        yield page.keys().press(page.keys().RIGHT);
                        currentItemFocus = yield page.getFocusedNode();
                        console.log(logger.modify.background.yellow(` inside while loop item focus node is ${JSON.stringify(currentItemFocus)}`));

                        hasMovedList= Object.values(currentItemFocus).includes(NAVIGATION_TO_LIST);
                        console.log(logger.modify.background.yellow(` has moved watchlist button status is ${(hasMovedList)}`));


                        moveNavigation++;
                    }

enter image description here

2 个答案:

答案 0 :(得分:0)

一旦hasMovedList为真,该代码将退出循环。将其设置为真实值后,只会发生在设置console.log的语句之后的moveNavigation++;hasMovedList。如果您不希望发生这种情况,请立即break

while (true) {
    yield page.keys().press(page.keys().RIGHT);
    currentItemFocus = yield page.getFocusedNode();
    console.log(logger.modify.background.yellow(` inside while loop item focus node is ${JSON.stringify(currentItemFocus)}`));

    if (Object.values(currentItemFocus).includes(NAVIGATION_TO_LIST)) {
        break;
    }
    console.log(logger.modify.background.yellow(` has moved watchlist button status is ${(hasMovedList)}`));

    moveNavigation++;
}

答案 1 :(得分:-1)

if的开头不需要while语句。要退出循环,您需要将hasMovedList更改为true