Home >Web Front-end >JS Tutorial >The problem of dynamically generating a table with N rows and N columns from a one-dimensional array

The problem of dynamically generating a table with N rows and N columns from a one-dimensional array

高洛峰
高洛峰Original
2016-11-28 13:19:541759browse

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+="&nbsp";}  
else{str+=arr[k+j*col];}  
str+="</td>";  
};//表格行结束  
str+="</tr>";  
};  
str+="</tbody></table>";  
   
document.body.innerHTML=str;


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn