javascript - 如何在函数中嵌套 if 语句?- Javascript
问题描述
既然我有一个递归函数,我想知道什么是最好的,以使相同的流程继续下去。
嵌套另一个函数,不是吗?
换句话说,我想要另一个提示,当用户对第一个提示回答是时询问用户的年龄。
我现在面临的问题是,如果用户写的不是“是”或“否”,最后一个提示不会回来。
他们嵌套的方式使提示以我无法弄清楚的方式弹出:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
function showPrompt(firstQuestion) {
var age = prompt(firstQuestion).toLowerCase();
if (age < 21) {
alert("You're too young. Go home.");
} else if (age >= 21) {
alert("Welcome.");
} else {
showPrompt(firstQuestion);
}
}
showPrompt("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?");
解决方案
问题是您正在覆盖您的功能。如果你给你的第二个函数取另一个名字,我猜它会按照你想要的方式工作。正如在另一个答案中给出的那样,您不需要在条件子句中定义您的函数:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
nextQuestion("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
function nextQuestion(secondQuestion) {
var age = parseInt(prompt(secondQuestion));
if (typeof age == "number" && age < 21) {
alert("You're too young. Go home.");
} else if (typeof age == "number" && age >= 21) {
alert("Welcome.");
} else {
showPrompt(secondQuestion);
}
}
showPrompt("Do you like gambling?");
推荐阅读
- c# - 转换日期格式 C#
- python - 查找每个键的最小值并基于键作为索引构建数组
- javascript - 用另一种方法达到变量的内容
- ui-automation - 使用 Selenium 的 Archer GRC 测试自动化
- wordpress - Carbon Fields 插件中的组
- django - 无法将类型整数转换为 uuid
- java - 如何配置 RSAKey.Builder 以生成没有空值的简单结果
- flutter - (Flutter) 如何正确使用 Consumer 和 ChangeNotifierProvider ?找不到丢失的东西
- javascript - 如何在 html 的画布元素中添加两个图像 ..?
- kotlin - TabLayoutMediator 从 kotlin 到 java