我创建了一个嵌套数组,至今为止我可以,但是我觉得我做错了或者没有任何意义。任何人都可以请看看,并告诉我,如果我的数组是建立嵌套数组的方式。我只想在特定标题下创建行,所以我嵌套数据并用嵌套循环调用它。也许这是一种更简单的方法。下面是代码:使用嵌套循环的Javascript嵌套数组
var data = [
{title:'Row Title 1'},
[{leftCol:'Some text for left column',rightCol:'Some text for right column'},
{leftCol:'Some text for left column',rightCol:'Some text for right column'},
{leftCol:'Some text for left column',rightCol:'Some text for right column'}],
{title:'Row Title 2'},
[{leftCol:'Some text for left column',rightCol:'Some text for right column'},
{leftCol:'Some text for left column',rightCol:'Some text for right column'},
{leftCol:'Some text for left column',rightCol:'Some text for right column'}]
];
for (var i=0, j=data.length; i < j; i++) {
if(data[i].title != null){
document.write('<b>'+data[i].title+'</b><br />');
}
for(p=0,plen=data[i].length; p<plen;p++){
document.write('<p style="background:#eee;">'+data[i][p].leftCol+'</p>');
document.write('<p>'+data[i][p].rightCol+'</p>');
}
}
是否有任何特定的原因,您选择使用数组而不是JSON? – jbabey
没理由。但是我的代码压缩了我的移动应用程序,我觉得我的数组做错了,因为如果我拿走标题“{title:'Row Title 1'}”,那么它就完美了。 – devjs11
你的代码破坏的原因是因为你的嵌套for循环不是有条件的(它检查对象'{title:'行标题1'}'和'{title:'行标题2'}'')的长度属性。将它包装在'else'范围内。 –