首页 > 解决方案 > 如何打破函数中的嵌套循环(javascript)

问题描述

我读过的很多答案都没有功能。但是,我绝对需要在我的脚本中包含函数。

var input = require('readline-sync')
var cart = [];
function func2() {
    console.log("this is the inner function")
    while (true) {
        firstinput = input.questionInt('Please Enter your input (1, 2, 3). Press 0 to Go back to outermost loop. You will still be in the program.')
        switch (firstinput) {
            case 0: 
                break; //breaks out of this entire func2()
            case 1: 
                func3()
                break; //breaks, but goes back to firstinput
            case 2:
                func4() //im not going to define it here, but similar to func3()
                func5() //im not going to define it here, but similar to func3()
                break;
            case 3:
                func5() 
                func3() //as you can see, the functions are recurring
                break;
            default:
                console.log('Input valid number, please')
                continue;
        }
    }
}

function func3() {

    while (true) {
        secondinput = input.question("Hi, please pick 1a, 1b, or 1c! You can Press 0 to exit to the outermost function. YOu will still be in the program, though")
        switch (secondinput) {
            case '0':
                break; //breaks out of func3() and func2()
            case '1a':
                cart.push("1a")
                break; //breaks out of func3()
            case '1b':
                cart.push("1b")
                break; //breaks out of func3()
            case '1c':
                cart.push('1c')
                break; //breaks out of func3()
            default:
                console.log('invalid input')
                continue;
        }
        
    }
}
function func1() {
    while (true) {
        func2()
        if ((secondinput == 0) || (firstinput == 0)) {
            console.log("I see you've pressed 0. Let's loop through again")
        }
        else {
            console.log('Here is what was in your cart: ' + cart)
        }
    }

}

func1()

我希望这很清楚!我需要打破内部功能和外部功能。这很难,因为如果我在函数中更改变量的值,外部的值不会改变。

先感谢您

我的问题是:当我进入 func3() 时,如果我按“0”,我该如何打破一切?

标签: javascriptnode.js

解决方案


您可以在想要停止函数时返回,或者继续保持循环。

while (true) {
    firstinput = input.questionInt('Please Enter your input (1, 2, 3). Press 0 to Go back to outermost loop. You will still be in the program.')
    switch (firstinput) {
        case 0: 
            return; //breaks out of this entire func2()
        case 1: 
            func3()
            continue; //breaks, but goes back to firstinput
        case 2:
            func4()
            func5() 
            continue;
        case 3:
            func5() 
            func3() //as you can see, the functions are recurring
            continue;
        default:
            console.log('Input valid number, please')
            continue;
    }
}

推荐阅读