在`array.push`一些字符串之后,数组会附加undefined。这是正常的吗?

时间:2012-04-25 12:16:56

标签: javascript

在将一些字符串推送到数组后,我在使用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()失败,因为信息未定义。当然我可以使用条件来跳过未定义的对象,但我想知道未定义的对象到底是怎么到达的。
我做错了什么?

2 个答案:

答案 0 :(得分:2)

formTagArr.push(buildForm(data));

你的buildForm函数没有返回任何内容,上面的代码试图将该函数的结果推送到数组中。没有return语句的函数最终会被定义为未定义。

似乎应该只是

buildForm(data)

由于此函数已经推送到formTagArr数组。

答案 1 :(得分:0)

jsfiddle

您需要删除formTagArr.push调用,并在displayForm调用中将行更改为:$(“#question-form”)。html(info);