首页 > 解决方案 > 如何在函数中嵌套 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?");

标签: javascriptfunctionif-statementnested

解决方案


问题是您正在覆盖您的功能。如果你给你的第二个函数取另一个名字,我猜它会按照你想要的方式工作。正如在另一个答案中给出的那样,您不需要在条件子句中定义您的函数:

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?");

推荐阅读