<script type="text/javascript">
var totalRows = new Array(10);
var goodMatches = new Array(6);
var min =1;
var max =10;
function getRandom(x,y)
{return Math.floor(Math.random() * (y - x + 1)) + x;}
function drawTable() {
var div_id = document.getElementById('div1');
var tbl = document.createElement("table");
tbl.setAttribute("id","table_id") ;
tbl.setAttribute("border","1") ;
div_id.appendChild(tbl);
var tabl_id = document.getElementById("table_id");
var div_id2 = document.getElementById('div2');
var node= " ";
for(var i=0;i<10;i++){
var row=document.createElement('tr');
totalRows[i]= new Array(10);
for(var j=0;j<10;j++){
var cell=document.createElement('td');
cell.setAttribute("width","100px") ;
cell.setAttribute("height","35px") ;
var k = getRandom(0,1000);
if ((k%2)==0)
{
totalRows[i][j] = document.createTextNode(getRandom(min,max));
}
else{
var z=getRandom(0,1000);
if ((z%2)==0)
{totalRows[i][j] = document.createTextNode("+");}
else
{totalRows[i][j] = document.createTextNode("-");}
}
cell.appendChild(totalRows[i][j]);
row.appendChild(cell);
}
tabl_id.appendChild(row);
}
} </script>
Retrieving from a 2D array
Page 1 of 12 Replies - 262 Views - Last Post: 02 February 2013 - 04:50 AM
#1
Retrieving from a 2D array
Posted 01 February 2013 - 11:43 PM
Hi i have created a table which display operators and operands randomnly. I want to retrieve every 3 element in each row. How can i proceed? can someone help?
Replies To: Retrieving from a 2D array
#2
Re: Retrieving from a 2D array
Posted 02 February 2013 - 01:15 AM
function values(){
var newArray;
var tableValues = " ";
var div_id2 = document.getElementById('div2');
newArray = totalRows.map(function(arrayNode){
return arrayNode.map(function(node){
tableValues+= node.nodeValue.trim();
div_id2.innerHTML = tableValues;
});
});
}
I managed to retrieve all the elements in the table as a string. But i need every 3 element to make a comparison. How can i do it?
#3
Re: Retrieving from a 2D array
Posted 02 February 2013 - 04:50 AM
Use the rows and cells collections:
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; j = j + 3 instead of j++
//columns would be accessed using the "col" variable
alert(col.firstChild.nodeValue); // or col.innerHTML;
}
}
This post has been edited by andrewsw: 02 February 2013 - 04:51 AM
Page 1 of 1
|
|

New Topic/Question
Reply


MultiQuote



|