数组表

时间:2017-05-29 01:57:38

标签: javascript html arrays html-table

我想从数组中创建一个表。我想要3行3列。行标题名称应为1,2,3。列应该是数组的名称:“country”,“Capital”,“population”。

这是我的HTML:

<!DOCTYPE html>
<html>
<head>
</head>
<body>    
    <script>        
    var country = ["Norway", "Sweden", "Denmark"];
    var capital = ["Oslo", "Stockholm", "Copenhagen"];
    var population = ["5,2", "9.8", "5,7"];    

</body>
</html>

2 个答案:

答案 0 :(得分:1)

以下是使用jQuery进行操作的示例。根据{{​​1}}的评论,我已将Roko C. Buljan更改为append

concatenation
//Array
var country = ["Norway", "Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm", "Copenhagen"];
var population = ["5,2", "9.8", "5,7"];

//Start the table
var table = '<table>';

//Add the Headers
table += '<thead><tr><th>Country</th><th>Capital</th><th>Population</th></tr></thead>';

//Start the body
table += '<tbody>';

//Add the inner rows
for (i = 0; i < country.length; i++) {
  table += '<tr><td>' + country[i] + '</td><td>' + capital[i] + '</td><td>' + population[i] + '</td></tr>';

}

//Close the body and the table
table += '</tbody></table>';

//Add the completed table to the HTML
$('#table').append(table);

答案 1 :(得分:0)

将数组嵌套到对象中。从那里通过重复细胞附着到桌子上。

var country = ["Norway","Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm", "Copenhagen"];
var population = ["5,2", "9.8", "5,7"];

var table={};
country.forEach((countries,key)=>
table[key]={country:countries,capital:capital[key],population:population[key]})
function tableCreate( table,l=Object.keys(table).length){
  var count=1;
 var body = document.body,
    tbl  = document.createElement('table');
    tbl.style.width  = '100px';
    tbl.style.border = '1px solid black';
    for(var i in table){
        var tr = tbl.insertRow();

 tr.appendChild(document.createTextNode(count));
      for(var j in table[i]){
           td = tr.insertCell(); 
          td.appendChild(document.createTextNode(table[i][j]));
          td.style.border = '1px solid black';     
        }
      count++
    }
    body.appendChild(tbl);
}
tableCreate(table);

var country = ["Norway","Sweden", "Denmark"];
var capital = ["Oslo", "Stockholm", "Copenhagen"];
var population = ["5,2", "9.8", "5,7"];

var table={};
country.forEach((countries,key)=>
table[key]={country:countries,capital:capital[key],population:population[key]})
function tableCreate( table,l=Object.keys(table).length){
 var body = document.body,
    tbl  = document.createElement('table');
    tbl.style.width  = '100px';
    tbl.style.border = '1px solid black';
    for(var i in table){
        var tr = tbl.insertRow();
        for(var j in table[i]){
            var td = tr.insertCell();
          td.appendChild(document.createTextNode(table[i][j]));
          td.style.border = '1px solid black';     
        }
    }
    body.appendChild(tbl);
}
tableCreate(table);