好的伙计们。这里的Javascript新手。 基本上,我需要写一个关于音乐的基本测验。我需要用户输入他们想到的答案,最后,它输出他们写的答案并告诉他们是否错误/正确。 我的逻辑是:
但我遇到的问题是userAnswers数组。我已经将它定义为空,但是当浏览器进入for循环时,它应该用用户答案填充它,但它不会因为我尝试在循环结束时打印出数组以查看它是否包含用户答案但是它不打印....
我的代码:
<!DOCTYPE>
<html>
<head>
<title> Quiz </title>
</head>
<body>
<input type="button" value="Start the quiz" name="quiz" onclick="gettingAnswers();" />
<script>
var questions = ["How many times did 50 cent get shot?",
"What year did Micheal Jackson die?",
"How many awards has Drake recieved as of January 2015?",
"What year did Kanye West win his first award?"];
var userAnswers = [];
function gettingAnswers ()
{
for(var i = 0; i < questions.length; i++)
{
var answers = prompt(questions[i]);
userAnswers[i] = answers;
}
}
document.write(userAnswers);
</script>
</body>
</html>
(原谅问题,想不出别的......)
答案 0 :(得分:1)
首先,您应该将写入移动到函数的末尾:
function gettingAnswers (){
for(var i = 0; i < questions.length; i++){
var answers = prompt(questions[i]);
userAnswers[i] = answers;
document.write(userAnswers);
}
userAnswers
是一个数组,而不是一个字符串。您可能希望将其更改为:
document.write(userAnswers.join("<br>"));
输出每个答案的,由html换行符分隔。
答案 1 :(得分:0)
移动“document.write(userAnswers);”在功能里面。我检查了它的确有效。
function gettingAnswers () {
for(var i = 0; i < questions.length; i++){
var answers = prompt(questions[i]);
userAnswers[i] = answers;
}
document.write(userAnswers);
}