我正在尝试实现一个算法来生成一个具有分层标题的表格。这些标题可以无限嵌套。
一个HTML渲染表格标记的示例可能如下所示:
标签的配置应当以以下JavaScript对象格式传递:
<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>
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渲染,只关注应该迭代配置的算法,以便以以下格式获得简单的2D数组:
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
你能帮助我吗?