Reputation: 8548
I can't seem to reach my object variables, I'm probably just doing a dummy mistake somewhere. A console.log of my array of objects (pResult) look like this, first object expanded but they all look alike:
[Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
depTime: "2014-12-04 18:35"
destination: "Norsesund station"
nr: "562"
operator: "Västtrafik"
typText: "Buss"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
length: 9
__proto__: Array[0]
I try to do this...
for (var i = 0; i <= pResult.length; i++) {
var html = html + '<tr>';
var html = html + '<td>';
var html = html + pResult[i].depTime;
var html = html + '</td>';
var html = html + '</tr>';
}
...but get hit with this error:
Uncaught TypeError: Cannot read property 'depTime' of undefined
Upvotes: 0
Views: 106
Reputation: 10499
Instead of using a loop, you can simply use reduce
:
var html = pResult.reduce(function(previousValue, currentValue) {
return previousValue + '<tr><td>' + currentValue.depTime + '</td></tr>';
}, '');
Note that this only works on IE 9+ (but it works in all other modern browsers), so if you need to support older versions of IE, you can polyfill the method.
Upvotes: 1
Reputation: 2040
try this:
for (var i = 0; i < pResult.length; i++) {
var html = '<tr>';
html += html + '<td>';
html += html + pResult[i].depTime;
html += html + '</td>';
html += html + '</tr>';
}
The problem is you are loopin until arrays length but array start at 0 index so
if you have array
var pResult= [object,object,object];
pResult.length =3
pResult[3]
doesnt exist so it is undefined.
NOTE dont recreate the variable when you just want to add text just add it to the existing one For example html+=" the added text"
Upvotes: 0
Reputation: 16068
Change :
i <= pResult.length;
To:
i < pResult.length;
Array is 0 based indexed, so if it has length 3, you only have indexes 0,1,2
Upvotes: 3