我似乎无法到达我的对象变量,我可能只是在某个地方做了一个虚拟的错误。对象数组( console.log of object,pResult)的pResult如下所示,第一个对象是展开的,但它们看起来都很相似:
[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]我试着这么做..。
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因此错误而被击中:
Uncaught TypeError: Cannot read property 'depTime' of undefined发布于 2014-12-04 18:03:19
改变:
i <= pResult.length;至:
i < pResult.length;数组是基于0的索引,因此如果数组的长度为3,则只有索引0、1、2。
发布于 2014-12-04 18:13:07
不需要使用循环,只需使用reduce
var html = pResult.reduce(function(previousValue, currentValue) {
return previousValue + '<tr><td>' + currentValue.depTime + '</td></tr>';
}, '');请注意,这只适用于IE 9+ (但它在所有其他现代浏览器中都能工作),因此如果您需要支持较早版本的IE,则可以对该方法进行多填充。
发布于 2014-12-04 18:12:33
试试这个:
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>';
}问题是,在数组长度之前都是loopin,但是数组从0开始,所以
如果你有数组
var pResult= [object,object,object];
pResult.length =3
pResult[3]不存在,所以它是未定义的。
注意:当您只想添加文本时,不要重新创建变量,只需将其添加到现有的变量中,例如,html+=“添加的文本”
https://stackoverflow.com/questions/27300863
复制相似问题