【发布时间】:2020-11-07 22:34:08
【问题描述】:
我有嵌套数组,我想列出属于他们父母的孩子。
但结果显然出错了,它列出了数组中的所有孩子,即使他们不属于父母。
就是想不出哪里出了问题。
var family = [
{ name:"parentOne",
children:[ "John", "jack"]
},
{ name:"parentTw0",
children: [ "jane", "joe"]
},
{ name:"parentThree",
children: [ "Terry", "Noah"]
},
]
all = "";
childAll = "";
for (i = 0; i < family.length; i++) {
for (j = 0; j < family[i].children.length; j++) {
childAll += family[i].children[j] +"<br>" ;
}
all += family[i].name + "<br>" + " " + childAll + "<br>";
}
document.getElementById("demo").innerHTML = all;
<p id="demo"></p>
【问题讨论】:
-
您需要在外部循环的开头重置
childAll,而不是在循环之前。目前,您将所有子项累积在该变量中。
标签: javascript for-loop nested-loops