在将一些字符串推入数组后,JavaScript数组添加了额外的未定义对象时遇到了麻烦。
$(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 /返回此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"]}]
和console.log(formTagArr);在上面的代码中返回:
["<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]
因此,由于未定义信息,因此displayForm()失败。当然,我可以使用条件跳过未定义的对象,但我想首先确切地知道未定义的对象是如何到达那里的。
我做错了什么?
最佳答案
formTagArr.push(buildForm(data));
您的buildForm函数不返回任何内容,上面的代码尝试将该函数的结果推入数组。没有return语句的函数将最终未定义。
似乎应该只
buildForm(data)
由于此功能已经推送到formTagArr数组。
关于javascript - 在将一些字符串添加到array.push之后,数组将附加未定义。那是正常的吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10315418/