本文介绍了使用简单数组中的javascript创建动态html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想写一些JavaScript来创建一个简单的HTML表格,它只包含数字: var array = [1,2,3,4,5,6,7,8,9,10]; 表格应该如下所示: 1 2 3 4 5 6 7 8 9 10 但JavaScript代码应该是动态的,取决于数组的大小(尽管总是5的因子)。 我尝试了很多东西,但它永远不会以我想要的方式工作。最简单的方法是什么? 这是我的一个尝试。 var tableStart =< table border>; (i = 0; i< arraySize / 5; i ++){ var tableMiddle =< tr>< td> 1< / td>< td> 2< / td> < TD> 3'; / TD>< TD> 4℃; / TD>< TD> 5℃; / TD>< / TR>中 if(arraySize / 5> = 2){ tableMiddle = tableMiddle + tableMiddle; } }; var tableEnd =< / table>; var table = tableStart.concat(tableMiddle,tableEnd); 以及 var result =< table border = 1>; for(var i = 0; i result + =< tr>; (var j = 0; j result + =< td>+ array [i] +< / td>; } 结果+ =< / tr>; } 结果+ =< / table>; 这个只会导致数组的两个值被显示很多次。解决方案您可以迭代数组并创建一个新行,如果5的余数为零。 $ b var array = [1,2,3,4,5,6,7,8,9,10], tr; array.forEach((v,i)=> {var td = document.createElement('td'); if(!(i%5)){tr = document.createElement('tr'); document。 getElementById('table0')。appendChild(tr);} td.appendChild(document.createTextNode(v)); tr.appendChild(td);}); < table id =table0>< / table> I want to write some JavaScript to create a simple HTML table from an array that just contains numbers:var array = [1,2,3,4,5,6,7,8,9,10];The table should look like this:1 2 3 4 56 7 8 9 10But the JavaScript code should be dynamic depending on the arrays size (always a factor of 5 though).I've tried a lot of stuff but it never works the way i want it to. What would be the easiest way to achieve this?This is one of my tries.var tableStart = "<table border>";for (i = 0; i < arraySize/5; i++){ var tableMiddle = "<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>" if (arraySize/5 >= 2) { tableMiddle = tableMiddle + tableMiddle; }};var tableEnd = "</table>";var table = tableStart.concat(tableMiddle, tableEnd);as well asvar result = "<table border=1>";for(var i=0; i<2; i++) { result += "<tr>"; for(var j=0; j<array.length; j++){ result += "<td>"+array[i]+"</td>"; } result += "</tr>";}result += "</table>";this one just results in two values of the array being displayed though a lot of times. 解决方案 You could iterate the array and build a new row if the remainder with 5 is zero.var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], tr;array.forEach((v, i) => { var td = document.createElement('td'); if (!(i % 5)) { tr = document.createElement('tr'); document.getElementById('table0').appendChild(tr); } td.appendChild(document.createTextNode(v)); tr.appendChild(td);});<table id="table0"></table> 这篇关于使用简单数组中的javascript创建动态html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-16 03:53