You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何根据行列数组生成矩阵并渲染为HTML表格

原代码问题说明

你的代码有两处核心bug:

  1. 矩阵初始化错误:Array(cols.length).fill(Array(rows.length).fill(0)) 会把同一个数组的引用填充到每一行,修改任意一行的数值时所有行都会同步变更;同时你把矩阵的行列维度写反了——最终矩阵的行数应该和subject数组(rows)长度一致,列数和note数组(cols)长度一致。
  2. 赋值逻辑错误:循环里你给矩阵赋值的是note字段,实际应该赋值value字段,且行列索引的对应关系搞反了。
修正后的矩阵生成代码
let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

// 初始化二维数组,每行都是独立的新数组,避免引用复用问题
let matrix = Array.from({ length: rows.length }, () => Array(cols.length).fill(0));
for (const item of notes) {
    const { note, subject, value } = item;
    const colPos = cols.indexOf(note);
    const rowPos = rows.indexOf(subject);
    // 过滤掉cols/rows里不存在的匹配项,避免索引为-1的报错
    if (colPos === -1 || rowPos === -1) continue;
    matrix[rowPos][colPos] = value;
}
console.log(matrix); // 输出结果为 [[10,0,0],[0,0,19]],完全符合预期
HTML表格渲染实现

拿到正确结构的matrix后,可以直接拼接DOM字符串生成你需要的表格结构:

// 拼接表格HTML
const tableHTML = `
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Subj\Note</th>
${cols.map(col => `<th>${col.replace('n', 'Note')}</th>`).join('')}
</tr>
</thead>
<tbody>
${rows.map((rowName, rowIndex) => `
<tr>
<td>${rowName.replace('subject', 'Subj')}</td>
${matrix[rowIndex].map(cellValue => `<td>${cellValue}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
</div>
`;

// 调用这段代码即可把表格插入页面,比如插入到body末尾:
// document.body.insertAdjacentHTML('beforeend', tableHTML);

内容的提问来源于stack exchange,提问作者TAHER El Mehdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 00:54:31