将用户输入的答案转换为小写并写入屏幕

时间:2019-03-20 06:28:54

标签: javascript

什么都没有写到屏幕上。

控制台错误显示以下内容:

  

ReferenceError:ans未定义**

这是代码:

预期结果应该是将提示符下的用户输入操纵为小写并写入页面。

将考虑任何帮助。

function lowerCase(ans) {
  var lowCase = ans.toLowerCase();
  return lowerCase;
}

var questions = ['How may strings does a violin have?', 'How many sides does an octagon have?',
  'How many NBA championships did Michael Jordan win with the Chicago Bulls?'
];

var answers = ['FOUR', 'EIGHT', 'SIX'];

var score = 0;

function quiz(counter) {
  var guesses = 3;

  while (guesses > 0) {
    var ans = prompt(questions[counter]);
    if (ans == answers[counter]) {
      alert("Correct!");
      return guesses;
    } else {
      guesses--;
      alert("Incorrect, You have " + guesses + " guesses remaining");
    }
  }
  return 0;
}

document.write(lowerCase(ans));

4 个答案:

答案 0 :(得分:1)

在函数中代替return lowerCase;进行return lowCase;。您将再次返回该函数,而必须返回包含小写字母文本的变量。在全局范围内而不是while循环内定义ans。您也必须调用测验功能。 document.write应该在测验功能之内而不是它之外

function lowerCase(ans) {
  var lowCase = ans.toLowerCase();
  return lowCase;
}

var ans='';

var questions = ['How may strings does a violin have?', 'How many sides does an octagon have?',
  'How many NBA championships did Michael Jordan win with the Chicago Bulls?'
];
var answers = ['FOUR', 'EIGHT', 'SIX'];

var score = 0;

function quiz(counter) {
  var guesses = 3;



  while (guesses > 0) {
     ans = prompt(questions[counter]);
    if (ans == answers[counter]) {
      alert("Correct!");
      return guesses;
    } else {
      guesses--;
      alert("Incorrect, You have " + guesses + " guesses remaining");
    }
  }
  document.write(lowerCase(ans));
}

quiz(2)

答案 1 :(得分:0)

您需要从函数中返回lowCase-同样,将document.write调用移至quiz函数中-最后,请调用quiz函数:

function lowerCase(ans) {
  var lowCase = ans.toLowerCase();
  return lowCase;
}



var questions = ['How may strings does a violin have?', 'How many sides does an octagon have?',
  'How many NBA championships did Michael Jordan win with the Chicago Bulls?'
];
var answers = ['FOUR', 'EIGHT', 'SIX'];

var score = 0;

function quiz(counter) {
  var guesses = 3;
  while (guesses > 0) {
    var ans = prompt(questions[counter]);
    if (ans == answers[counter]) {
      alert("Correct!");
      document.write(lowerCase(ans) + "<br>");
      return guesses;
    } else {
      guesses--;
      alert("Incorrect, You have " + guesses + " guesses remaining");
    }
  }
  return 0;
}

document.write("You had " + quiz(2) + " guesses remaining after the game ended");

答案 2 :(得分:0)

列出错误后,只需稍作更改,ReferenceError:ans尚未定义。发生这种情况的原因是,您正在使用参数 ans 调用函数LowerCase,但是 ans 仅在代码的while循环内包含作用域,因此最好将其定义为全局变量并在此处使其空白,之后可以覆盖条件/循环中的值。 希望这能解决您的问题。

答案 3 :(得分:0)

我已修复代码注释更改。您似乎有范围问题。他们用这种方式编写了ans变量,该变量在文档写入时不可见。我修复了其他一些错误。

{{1}}