<分区>
对于所有 javascript/jquery 的人来说,这将是一个非常简单的问题。
过去 2 年我一直在编写 javascript,今天我遇到了一个奇怪的问题。
我正在从我的 C# Webmethod
中获取一个 JSONarray 并通过 jQuery.ajax()
调用它
当我做的时候
for (i in JSONRaw) {
Index = Index + 1;
$('#bottomGridDashboard').append('<tr> <td>' + Index + '</td> <td>' + JSONRaw[i].DisplayName + '</td> <td>' + JSONRaw[i].SpeedInKPH + '</td> <td><img src="' + JSONRaw[i].ImageURL + '" height="20px" alt="" /></td> <td>' + JSONRaw[i].DepotID + '</td> <td>' + JSONRaw[i].RouteID + '/' + JSONRaw[i].ScheduleID + '/' + JSONRaw[i].TripID + '</td> <td>' + JSONRaw[i].Direction + '</td> <td>' + JSONRaw[i].LastStop + '</td> <td> ' + JSONRaw[i].ETAMinutes + ' </td> </tr>');
}
附加表添加了两个额外的行,将每个字段都设置为“未定义”。 See this Image
但是,如果我用
替换循环for (var i = 0; i < JSONRaw.length;i++ ) {
Index = Index + 1;
$('#bottomGridDashboard').append('<tr> <td>' + Index + '</td> <td>' + JSONRaw[i].DisplayName + '</td> <td>' + JSONRaw[i].SpeedInKPH + '</td> <td><img src="' + JSONRaw[i].ImageURL + '" height="20px" alt="" /></td> <td>' + JSONRaw[i].DepotID + '</td> <td>' + JSONRaw[i].RouteID + '/' + JSONRaw[i].ScheduleID + '/' + JSONRaw[i].TripID + '</td> <td>' + JSONRaw[i].Direction + '</td> <td>' + JSONRaw[i].LastStop + '</td> <td> ' + JSONRaw[i].ETAMinutes + ' </td> </tr>');
}
未定义的行消失.. See the image
我为我的愚蠢道歉,但我以前从未遇到过任何此类问题。 可能是什么原因??
编辑:
数组非常好。而且里面没有洞。 另一个观察是未定义的属性只出现在我的网格底部。我认为它正在处理两个多于数组长度的额外索引。
EDIT-2
我的 console.log 显示了数组中的以下元素。
http://i.imgur.com/rI5TjdK.jpg
我已经在我的母版页中声明了原型(prototype)。
Array.prototype.inArray = function (comparer) {
for (var i = 0; i < this.length; i++) {
if (comparer(this[i])) return true;
}
return false;
};
Array.prototype.pushIfNotExist = function (element, comparer) {
if (!this.inArray(comparer)) {
this.unshift(element);
}
};
是否增加数组长度。 ? ?