How to iterate over a table in Javascript and change the specified cells with each other?

I have a table with the ID "mytable", and I have a for loop that builds a 4x4 table, giving each cell an ID between 0 and 15 and setting innerHTML to the same number. When a cell is left blank, as it will be part of an unfolding puzzle game where the user presses a button that scrambles the table cells, solves it by shifting the cell positions into that blank space. My problem at the moment is that I cannot implement the shuffle function that works. Below is my code for my table building and shuffling. See the comments for the bug report.

function buildTable(){//need to build it with every cell being named
    var tablelocation = document.getElementById('mytable'); 
    var table = document.createElement('table');
    table.id="newtable";
    for(var i = 0; i<tableSize; i++){
        var tableRow = table.insertRow();
        for(var j = 0; j<tableSize; j++){
            var arrTmp = (tableSize*tableSize-1)-(i*tableSize+j);
            var cell = tableRow.insertCell();
            cell.id = arrTmp;       
            if(arrTmp==15){
                cell.className = "empty_cell";
            else{
                cell.className = "cell";    
                cell.appendChild(document.createTextNode(arrTmp));
            }

        }
    }

    tablelocation.appendChild(table);
}

      

Since the table is built from the bottom right top left corner, I have a variable that processes the values ​​so that once the table is built, the numbers appear in the table from 0 to 15 in the upper left upper left.

function shuffleTable(){//need to build it with every cell being named


    var table = document.getElementById("newtable");
    for (var i = 0; i<tableArray.length; i++) {
        var tmp = tableArray[i];//array of shuffled ID values
        var tmp2 = objectCellArray[tmp];
        objectCellArrayShuffled.push(tmp2);
    }
    for (var j = 0; j<tableArray.length; j++){
        var cell = table.cells[j];//fails here with undefined is not an object error
        cell = objectCellArrayShuffled[j];
    }
}

      

I am calling shuffleTable with a button in my html page.

+3


source to share





All Articles