This would be a very easy question for all you javascript/jquery guys.
I've been programming javascript from past 2 years and today I faced a strange problem.
I am fetching a JSONarray from my C# Webmethod
and calling it by jQuery.ajax()
When I do
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>');
}
the appended table adds two extra rows putting every field as 'undefined'. See this Image
However if i replace the loop with
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>');
}
the undefined rows disappear.. See the image
I apologize for my stupidity but I have never faced any such problem before. What could be the reason??
EDIT:
The array is perfectly fine. And there are no holes in it. Another observation is that the undefined properties appear only at the bottom of my grid. I think it is processing two extra indexes more than the array length.
EDIT-2
My console.log showed me the following elements in my array.
https://i.stack.imgur.com/jw8Sy.jpg
I've declared the prototypes in my Master page.
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);
}
};
Is it increasing the array length. ? ?