在表上显示2d数组?使用Javascript

时间:2013-10-30 16:54:44

标签: javascript

我正在创建一个带用户输入的二维数组。如何在3×3表格上显示输入?

<script language = javascript>
var b = [];
for(var i=0; i<3; i++){
b[i] = [];
for(var j=0; j<3; j++){
b[i][j] = window.prompt("b["+(i+1)+","+(j+1)+"] = ?");
}
}
</script>
</head>
<body>
<table width="80%" border="2" cellspacing="0" cellpadding="0">
  <tr>
<td> </td>
<td>&nbsp;</td>
<td>&nbsp;</td>
 </tr>
 <tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>

2 个答案:

答案 0 :(得分:2)

你可以这样做......

<!DOCTYPE html>
<html>
<head>
<style>
table {
    font: 11px/24px Verdana, Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 320px;
    }

td {
    border: 1px solid #CCC;
    padding: 0 0.5em;
    }


</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>

$(document).ready(function(){



$("#myRandomizeBtn").bind("click",randomizeHandler); 

function randomizeHandler(evt){     
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
tab.className="mytable";
var tbo=document.createElement('tbody');
var row, cell;
var n = 3;  
var data;    

for (i=0; i<n; i++)
{
    row=document.createElement('tr');
    for(var j=0;j<n;j++){
        cell=document.createElement('td');
        data =window.prompt("b["+(i+1)+","+(j+1)+"] = ?"); 
        cell.appendChild(document.createTextNode(data));
        row.appendChild(cell);
    }
    tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);




   }  



});
</script>
</head>
<body>
    <div id='mydiv'></div>
    <button id = "myRandomizeBtn">Randomize</button> 
</body></html>

这是一个有效的fiddle

答案 1 :(得分:1)

您可以使用以下代码遍历和推送值

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop

       col.innerText = b[i][j]; //Set your value here   
   }  
}

Working Demo

来自@John Hartsock的参考文件回答How do I iterate through table rows and cells in javascript?