I’m having trouble with a JavaScript array adding an extra undefined object after pushing some strings to the array.
$(function() {
var formTagArr = [];
$( "button", "#start-button" ).click(function() {
$.getJSON('http://127.0.0.1:8000/some_url/', function(data) {
formTagArr.push(buildForm(data));
console.log(formTagArr);
displayForm(formTagArr);
});
return false;
});
function buildForm(data) {
for (var i = 0; i < data.length; i++) {
var html = "";
var questionsTags = "<fieldset><p>" + data[i].question + "</p>";
var answersTags = "";
for (j = 0; j < data[i].answers.length; j++) {
answersTags += "<input type='radio' name='" + data[i].qid +
"' value='" + data[i].answers[j] + "' /" + ">" +
data[i].answers[j] + "\n";
}
html = questionsTags + answersTags + "</fieldset>";
formTagArr.push(html);
}
}
function displayForm(arr) {
if (arr.length === 0) {
return false;
}
var info = arr.pop();
$("#question-form").append(info[0]);
}
});
/some_url/ returns this JSON:
[{"qid": 4, "question": "How many legs does a spider have?", "answers": ["4", "6", "8", "10"]}, {"qid": 2, "question": "When did Nigeria become a republic?", "answers": ["1960", "1961", "1962", "1963"]}, {"qid": 1, "question": "When did Nigeria gain independence?", "answers": ["1960", "1961", "1962", "1963"]}, {"qid": 3, "question": "How many days are in a leap year?", "answers": ["360", "362", "365", "366"]}]
and console.log(formTagArr); in the code above returns:
["<fieldset><p>How many l...e='10' />10\n</fieldset>", "<fieldset><p>When did N...963' />1963\n</fieldset>", "<fieldset><p>When did N...963' />1963\n</fieldset>", "<fieldset><p>How many d...'366' />366\n</fieldset>", undefined]
Because of this, displayForm() fails since info is undefined. Of course I could just use a conditional to skip the undefined object but I want to know exactly how the undefined object got there in the first place.
What did i do wrong?
Your buildForm function doesn’t return anything and the above code try to push the result of that function into the array. A function without a return statement would end up as undefined.
Seems like it should only be
As this function already pushed to the formTagArr array.