我知道迭代已经被覆盖过 - 我通常对它很好但是这次很挣扎。
我有以下信息,我试图循环:
Object { leaving: object { all: array[10] } }
我可以通过返回来轻松返回单个结果:
var html = '<p>' + news.leaving.all[0].departure_time + '</p>';
但是当我尝试循环时:
var html = "";
var i;
for (i = 0; i < news.length; i++) {
html +=
'<p>' + news[i].leaving.all.departure_time '</p>';
}
我一无所获......
对此的任何帮助都会很棒。
由于
答案 0 :(得分:3)
看起来你需要
'<p>' + news.leaving.all[i].departure_time '</p>';
而不是
'<p>' + news[i].leaving.all.departure_time '</p>';
并改变
for (i = 0; i < news.length; i++) {
到
for (i = 0; i < news.leaving.all.length; i++) {
答案 1 :(得分:2)
您还必须遍历“所有”成员:
var html = "";
for (var i = 0; i < news.leaving.all.length; j++) {
html +=
'<p>' + news.leaving.all[i].departure_time '</p>';
}
答案 2 :(得分:1)
您可以使用Array.prototype.forEach()迭代数组news.leaving.all
。
代码示例:
var news = {leaving: {all: [{departure_time: '01:00'},{departure_time: '02:00'},{departure_time: '03:00'}]}},
html = "";
news.leaving.all.forEach(function (n) {
html += '<p>' + n.departure_time + '</p>';
});
console.log(html);
答案 3 :(得分:0)
你必须循环news.leaving.all
:
// Let's say this is our data
var news = {
leaving: {
all: [{
departure_time: '01:00'
},
{
departure_time: '02:00'
},
{
departure_time: '02:00'
}]
}
};
var html = "";
var i;
for (i = 0; i < news.leaving.all.length; i++) {
html += '<p>' + news.leaving.all[i].departure_time + '</p>';
}
console.log(html);