<html>
<body>
<script type="text/javascript">
var categoryGroups = [
{
Id: 1, Categories:
[
{ Id: 1 },
{ Id: 2 },
]
},
{
Id: 2, Categories: [
{ Id: 100 },
{ Id: 200 },
]
}
]
var category, categoryGroup, found = false;
for (i = 0; i < categoryGroups.length ; i++) {
categoryGroup = categoryGroups[i];
for (j = 0; j < categoryGroup.Categories.length; j++) {
category = categoryGroup.Categories[j];
if (category.Id === categoryGroup.Id) {
found = true;
break;
window.document.write("category" );
}
}
if (found) break;
}
</script>
</body>
</html>
我已经创建了嵌套数组。从这个嵌套数组我想打印一个嵌套数组的对象。但无法找到嵌套数组的对象。如何解决这个错误?
最佳答案
将break;
移到输出下方,因为break
结束迭代,并且后面的任何内容都不会执行。
window.document.write("category");
break;
var categoryGroups = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 }, ] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }, ] }],
category, categoryGroup, found = false, i, j;
for (i = 0; i < categoryGroups.length ; i++) {
categoryGroup = categoryGroups[i];
for (j = 0; j < categoryGroup.Categories.length; j++) {
category = categoryGroup.Categories[j];
if (category.Id === categoryGroup.Id) {
found = true;
window.document.write("category " + category.Id); // swap
break; // lines
}
}
if (found) break;
}