【发布时间】:2016-05-26 15:14:42
【问题描述】:
我正在尝试实现一种算法来生成带有分层标题的表。这些可以无限嵌套。 呈现的表格标记的 html 示例如下:
<table border=1>
<thead>
<tr>
<th colspan="6">
Super one
</th>
<th colspan="6">
Super two
</th>
</tr>
<tr>
<th colspan="3">Head one</th>
<th colspan="3">Head two</th>
<th colspan="4">Head three</th>
<th colspan="2">Head four</th>
</tr>
<tr>
<th>Sub one</th>
<th>Sub two</th>
<th>Sub three</th>
<th>Sub four</th>
<th>Sub five</th>
<th>Sub six</th>
<th>Sub seven</th>
<th>Sub eight</th>
<th>Sub nine</th>
<th>Sub ten</th>
<th>Sub eleven</th>
<th>Sub twelve</th>
</tr>
</thead>
</table>
表格的配置应该以这种格式作为JavaScript对象传递:
var columns = [
{
label: 'Super one',
children: [
{
label: 'Head one',
children: [
{label: 'Sub one'},
{label: 'Sub two'},
{label: 'Sub three'}
]
},
{
label: 'Head two',
children: [
{label: 'Sub four'},
{label: 'Sub five'},
{label: 'Sub six'}
]
}
]
},
{
label: 'Super two',
children: [
{
label: 'Head three',
children: [
{label: 'Sub seven'},
{label: 'Sub eight'},
{label: 'Sub nine'},
{label: 'Sub ten'}
]
},
{
label: 'Head four',
children: [
{label: 'Sub eleven'},
{label: 'Sub twelve'}
]
}
]
}
];
现在,让我们忘记 html 渲染,只关注应该迭代配置的算法,以便获得一个简单的二维数组格式:
var structure = [
[6, 6],
[3, 3, 4, 2],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];
其中每个条目表示包含其列定义 (td) 的表行 (tr),数字表示 colspan。
如何实现算法?
目前我创建了一个递归函数,它根据配置返回总列数:
function getColumnCount(columns) {
var count = 0;
for (var i=0; i<columns.length; i++) {
var col = columns[i];
if (col.children && col.children.length > 0) {
count += getColumnCount(col.children);
}
else {
count++;
}
}
return count;
}
它按预期工作,但我一直在尝试生成“结构”数组...我当前(令人尴尬的)代码尝试是这样的:
function getStructure(columns) {
var structure = [[]];
for (var i=0; i<columns.length; i++) {
var col = columns[i];
if (col.children && col.children.length > 0) {
console.log(col.label, '(with children)');
schema[structure.length - 1].push(getColumnCount(col.children));
getStructure(col.children, schema);
}
else {
console.log(col.label, '(orphan)');
schema[structure.length - 1].push(1);
}
}
return structure;
}
我觉得自己真的很笨,因为我知道这应该是一项相对容易的任务,但是当涉及到递归函数时,我的大脑似乎拒绝协作 XD
你能帮帮我吗?
【问题讨论】:
-
配置中的所有兄弟都有深度?
-
我猜你的意思是如果他们有 same 深度......在这种情况下,好问题......我应该能够处理不同的深度......例如“头四”可以不配置“子十一”和“子十二”
-
你能给我举个例子说明
structure应该是什么样子吗?
标签: javascript arrays algorithm recursion