有没有办法从函数内定义的变量中获取信息?

时间:2017-03-10 05:36:33

标签: javascript function variables if-statement typescript

我试图找出是否有办法访问存储在函数内部定义的变量中的信息?我对如何做我想在这里做的事感到困惑......

注意:这不是完整的代码,而是我需要帮助的代码片段。

let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
firstQuestion();


function firstQuestion(){
  let someAnswer = prompt(question1.questionName + " " + question1.questionString);
}

if (someAnswer == "poppy"){

我正在尝试使用if语句来确定问题答案是否正确,但我不能这样做,因为someAnswer在函数内定义....我不确定是否有办法不使用函数来做到这一点?

更新

好的,我得到了那个工作,但现在我的代码的if / else语句不起作用。如果我给出了错误的答案,它说我有正确的答案。我真的没有看到任何合乎逻辑的理由......

//store score total

让pointsCount = 0;

//questions
class Question {
questionName: string;
questionString: string;

constructor(questionName:string, questionString:string){
  this.questionName = questionName;
  this.questionString = questionString;
}
}


//question one
let question1 = new Question("What is the California State Flower?", "1. Rose. 2. Tulip. 3. Poppy.");
let firstAnswer = firstQuestion();
function firstQuestion(){
  return prompt(question1.questionName + " " + question1.questionString);
}

if (firstAnswer === "Poppy" || "poppy"){
  pointsCount ++;
alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");

} else {
  alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");

}


//question two

let question2 = new Question("What is the California State Bird?","1. Quail. 2. Eagle. 3. Penguin.")

let secondAnswer = secondQuestion();

function secondQuestion(){
  return prompt(question2.questionName + " " + question2.questionString);
}

if (secondAnswer === "quail" || "Quail"){
  pointsCount++;
  alert("You got it!" + " " + "You now have" + " " + pointsCount + " " + "points!");
} else if (secondAnswer !== "quail" || "Quail") {
    alert("Wrong!" + " " + "You now have" + " " + pointsCount + " " + "points!");
  }

2 个答案:

答案 0 :(得分:1)

你关闭;你没有从你的firstQuestion函数返回任何内容,所以当你运行它时,什么都不会发生。

let question1 = new Question("What is California State Flower?", "1. Rose. 2. Tulip. 3. Poppy");
let answer = firstQuestion();


function firstQuestion(){
  //  return whatever the user enters in the prompt
  return prompt(question1.questionName + " " + question1.questionString);
}

if (answer.toLowerCase() == "poppy"){
  // call .toLowerCase on your answer to ensure you've covered capitalization edge-cases
}

答案 1 :(得分:0)

也许这就是你需要的

let someAnswer;
function firstQuestion(){
  someAnswer = prompt(question1.questionName + " " + question1.questionString);
}