错误
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>");
}
}
为什么这个回复[i]未定义?
答案 0 :(得分:3)
它应该是i < size
,因为数组索引是从0
到length-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]
的值未定义时
答案 1 :(得分: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>");
}
答案 2 :(得分: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>");
}
}
如果仅使用过滤后的大小,则使用过滤后的数组来避免空值或未定义的值。我也是&lt;大小。