Eternal loop in a simple HTML-form-creating loop
I'm trying to make this simple code of creating 3 multiple-choice question out of a JSON data, For reason beyond my comprehension what happens is an eternal loop, in which the last question is written to the page again and again until it crashes... Help and advice would be highly appreciated.
var questions = {
"qestion":["what is bla?", "what is bla bla?", "what is bla bla bla?"],
"answer":[["aaa","bbb","ccc","ddd"], ["eee","fff","ggg","hhh"], ["zzz","xxx","yyy","www"]],
"correctAns":[1,2,3]};
String.prototype.format = function() {
var formatted = this;
for (i=0; i< arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
function writeQuestions() {
for (i=0 ;i<=2; i++) {
answerRdy = [];
qestionRdy = questions.qestion[i];
answerRdy[0] = questions.answer[i][0];
answerRdy[1] = questions.answer[i][1];
answerRdy[2] = questions.answer[i][2];
answerRdy[3] = questions.answer[i][3];
divID = "question-" + i;
writeAnswer = [];
writeAnswer[writeAnswer.length] = ("\n<div id='{0}'>\n<form method='post' onsubmit='return validate(this);'>\n").format(divID);
writeAnswer[writeAnswer.length] = ("<b>" + qestionRdy + "</b><br />\n");
for (n=0; n<=3; n++) {
writeAnswer[writeAnswer.length] = ("<input type='radio' name='answer' value='{0}' /> {1} <br />\n").format(n, answerRdy[n]);
}
writeAnswer[writeAnswer.length] = ("<input type='submit' value='Submit your answer'>\n</form>\n</div><!--{0}-->").format(divID);
joinQuestion = writeAnswer.join();
exp = /,/gi;
fullQuestion = joinQuestion.replace(exp, "");
$('#co开发者_Go百科ntainer').append(fullQuestion);
}
}
I changed you for loops to declare local variables for iteration and also linked the termination length to the appropriate object and that seemed to do the trick. For example:
for (i=0 ;i<=2; i++) {
became:
for (var i = 0, len = questions.answer.length; i < len; i++) {
See example →
Could it because your have two for loops that use an un-declared magic global variable "i"
for (i=0...
where it should most likely be
for (var i=0...
精彩评论