0

错误

TypeError: response[i] is undefined


    ...box' class='selectedSubjects' name='selectedSubjects' />
</td><td class='selected...

大批

[{"S_Code":"BCS-CER-IS","S_Name":"Information Systems.","C_Code":"BCS-CER","S_Status":"Active"},
{"S_Code":"BCS-CER-SD","S_Name":"Software Development.","C_Code":"BCS-CER","S_Status":"Active"},
{"S_Code":"BCS-CER-TEC","S_Name":"Computer & Network Technology","C_Code":"BCS-CER","S_Status":"Active"}]

AJAX 成功回调

success: function (response) {
    var size = response.filter(function (value) {
        return value !== undefined
    }).length;
    for (var i = 0; i <= size; i++) {
        $("#subjectsTable tr:last").after("<tr class='success' data-index=" + (i + 1) + "><td><input type='checkbox' class='selectedSubjects' name='selectedSubjects' /></td><td class='selectedSCode'>" + response[i].S_Code + "</td><td class='selectedSName'>" + response[i].S_Name + "</td></tr>");

    }
}

为什么这个 response[i] 是未定义的?

4

3 回答 3

3

它应该是i < size数组索引从0length-1

for (var i = 0; i < size; i++) {
    $("#subjectsTable tr:last").after("<tr class='success' data-index=" + (i + 1) + "><td><input type='checkbox' class='selectedSubjects' name='selectedSubjects' /></td><td class='selectedSCode'>" + response[i].S_Code + "</td><td class='selectedSName'>" + response[i].S_Name + "</td></tr>");

}

所以当i == size的值response[i]未定义时

于 2013-09-06T05:55:33.147 回答
0

像这样的东西会起作用

for (var i = 0; i <= (size - 1); i++) {
        $("#subjectsTable tr:last").after("<tr class='success' data-index=" + (i + 1) + "><td><input type='checkbox' class='selectedSubjects' name='selectedSubjects' /></td><td class='selectedSCode'>" + response[i].S_Code + "</td><td class='selectedSName'>" + response[i].S_Name + "</td></tr>");
    }
于 2013-09-06T05:59:14.653 回答
0

将其更改为:

success: function (response) {
    var filtered = response.filter(function (value) {
        return value !== undefined
    });
    var size = filtered.length;

    for (var i = 0; i < size; i++) {
        $("#subjectsTable tr:last").after("<tr class='success' data-index=" + (i + 1) + "><td><input type='checkbox' class='selectedSubjects' name='selectedSubjects' /></td><td class='selectedSCode'>" + filtered[i].S_Code + "</td><td class='selectedSName'>" + filtered[i].S_Name + "</td></tr>");

    }
}

如果您只取过滤后的大小,则使用过滤后的数组来避免空值或未定义值。我也 < 大小 。

于 2013-09-06T06:04:44.873 回答