Someone asked me a question just now. The content of the question is roughly as follows:
Now I need to generate a 7-column table. All the contents of the table are stored in a JavaScript one-dimensional array. How to achieve this?
I tried to write the following code, firstly, to keep it as a souvenir, and secondly, in case I need it in the future, I don’t have to look for it everywhere.
The specific code and corresponding comments are as follows:
var arr=[]; var col=7;//这里为生成7列的表格 for (var i=0;i<25;i++){arr[i]=i;}//这里只是举例子,在实践中应该为具体数据 var lines=Math.ceil(arr.length/col);//很关键的一步,这里为生成表格的行数 var str="<table><tbody>";//表头 for (var j=0;j<lines;j++){//遍历表格行 str+="<tr>"; for (var k=0;k<col;k++){//遍历表格列 str+="<td>"; if(typeof arr[k+j*col]=="undefined"){str+=" ";} else{str+=arr[k+j*col];} str+="</td>"; };//表格行结束 str+="</tr>"; }; str+="</tbody></table>"; document.body.innerHTML=str;