为什么 Java 脚本嵌套循环出错了?

why Java Script nested loop gone wrong?

我有嵌套数组,我想列出属于其 parenets 的 children。

但是结果显然出错了,它列出了数组中所有的children,即使它们不属于parents。

只是无法弄清楚出了什么问题。

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>

在第一个 for 循环中创建 childAll = "",因为您想从每个父级的空列表开始。

它不会重置 childAll。

all = "";
childAll = "";
for (i = 0; i < family.length; i++) {
    // After one loop the childAll contains all the previous ones
    for (j = 0; j < family[i].children.length; j++) {
        childAll += family[i].children[j] +"<br>" ;
    }

  all += family[i].name + "<br>" + " " + childAll + "<br>";
}

应该是

all = "";
for (i = 0; i < family.length; i++) {
    // Reset every loop
    childAll = "";

    for (j = 0; j < family[i].children.length; j++) {
        childAll += family[i].children[j] +"<br>" ;
    }

  all += family[i].name + "<br>" + " " + childAll + "<br>";
}