javascript - 如何打破函数中的嵌套循环(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”,我该如何打破一切?
解决方案
您可以在想要停止函数时返回,或者继续保持循环。
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;
}
}
推荐阅读
- javascript - 聚合 Mongo DB
- javascript - 尝试在 bottomSheet 上启动片段时应用程序崩溃
- c# - 将 XmlWriter 文件名保存到变量
- kubernetes - 在 Kubernetes 上部署 2 层应用程序。ClusterIP 和负载均衡器
- python - pandas:创建 n 个新列以包含最后 n 个值(滚动)
- django - "
":["此字段为必填项。"] 消息 Django REST 框架 - java - 如何将对象传递给 Thymeleaf 中的模态对话框?
- python-3.x - 如何生成将显示正态分布倒钟形曲线的数据
- vue.js - 如何在一个路由的路径中添加路由器 vue.js 一字异常?
- python - 字典解包操作符与 copy.deepcopy 之间的区别?