如何用JavaScript正确填充表格列?代码出现undefined与重复问题
解决嵌套对象数组生成表格的问题
问题现象
基于嵌套对象数组生成两列表格时,表头出现undefined值,且处理器型号和频率内容各自单独成行,无法对应显示。
问题原因
- 表头重复且出现undefined:原数组分为两个独立对象,循环数组时每次都创建表头行,第一个对象没有
titleTwo,第二个对象没有titleOne,导致两次表头行分别出现undefined。 - 内容无法对应:循环每个对象的values时,只创建一个单元格,导致处理器和频率各自占一行,无法在同一行配对。
修正后的代码
JavaScript代码
let processorFrequency = [ { titleOne: 'Processor', values: [ {name: '80386LC (1988г.)'}, {name: '80486DX4 (1994г.)'}, {name: 'Pentium MMX (1997г.)'}, {name: 'Pentium II (1998г.)'}, {name: 'Pentium III (1999г.)'}, {name: 'Pentium IV'}, {name: 'Athlon-Athlon XP'}, {name: 'Athlon 64'} ] }, { titleTwo: 'Processor frequency', values: [ {name: '33-60'}, {name: '80-133'}, {name: '160-233'}, {name: '260-550'}, {name: '300-1400'}, {name: '1600-3800'}, {name: '1400-3200'}, {name: '2600-3800'} ] } ]; function Test() { const table = document.getElementsByTagName('table')[0]; // 创建单独的表头行 const headerRow = document.createElement('tr'); // 填充表头内容 const th1 = document.createElement('th'); th1.textContent = processorFrequency[0].titleOne; th1.className = 'head'; headerRow.appendChild(th1); const th2 = document.createElement('th'); th2.textContent = processorFrequency[1].titleTwo; th2.className = 'head'; headerRow.appendChild(th2); table.appendChild(headerRow); // 提取两组数据数组 const processorList = processorFrequency[0].values; const frequencyList = processorFrequency[1].values; // 循环生成内容行,确保同一索引的内容配对 for (let i = 0; i < processorList.length; i++) { const row = document.createElement('tr'); const processorTd = document.createElement('td'); processorTd.textContent = processorList[i].name; row.appendChild(processorTd); const frequencyTd = document.createElement('td'); frequencyTd.textContent = frequencyList[i].name; row.appendChild(frequencyTd); table.appendChild(row); } } Test();
CSS代码
table td, table th { border: 1px solid black; padding: 5px; }
HTML代码
<table><!-- Contents will be created via JavaScript --> </table>
说明
- 单独创建表头行,避免重复生成和undefined问题;
- 通过索引配对处理器和频率数据,确保每行显示一组对应内容;
- 保留原数组的属性名,无需额外修改数据结构。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

