我现在才开始学习。你能帮帮我吗,为什么我没有得到正确的输出。这是我的代码:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
我一遍又一遍地看了这段代码,但我仍然无法理解为什么我的结果未定义。在调试器中,在循环之后我检查我的变量,一切似乎都没问题。
答案 0 :(得分:3)
在printResult函数中,您使用的是var i而不是j,
另外,您最好使用innerHtml + = message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
答案 1 :(得分:2)
你的主要错误是使用我的j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}
答案 2 :(得分:2)
基本上你有三个问题。
重用oList
,该变量应在声明内部并仅在printResult
中使用。
在printResult
内,使用已使用i
的{{1}}
在j
,您可以使用新内容替换实际内容。
只是一个小变量,带有用于计数的变量名称。最好始终使用print
而不是i
开始,然后继续使用字母表中的字母。
j
&#13;