mercredi 10 octobre 2018

JavaScript- array size doubles after shuffling even with slice()

I have an array of 5 words that I want to randomly place on a section of an HTML table. When I run the code below, the keywords randomly appear on the table but their numbers are doubled (I get a total of 10 words on the grid). I am not sure why the cloning with slice does not work. I am new to JS and don't understand all its technicalities yet. Any feedback on what I might be doing wrong would be appreciated.

var keywords = ["s1", "s2", "s3", "s4", "s5"];
function shuffle(array) {
  var currentIndex = array.length, temp, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temp = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temp;
} 
 return array;
}
function drawBoard(rows, cols){
    var grid = document.getElementById("grid");
    grid.className = 'grid';
    for (var r = 0; r < rows; r++){
        var row = grid.appendChild(document.createElement('tr'));
        for (var c = 0; c < cols; c++){
            var cell = row.appendChild(document.createElement('td'));
        }       
    }
    grid.rows[0].cells[0].innerHTML = "START";
    grid.rows[7].cells[7].innerHTML = "FINISH";
    const filtered = Array.from(grid.querySelectorAll('td')).filter(({cellIndex, parentElement: {rowIndex}}) => rowIndex  && rowIndex < ROW - 1 && cellIndex && cellIndex < COL -1);
    shuffle(filtered);
    const sliced = filtered.slice(0, keywords.length);
    const index = Math.floor(Math.random() * keywords.length);
    sliced.forEach((cell, index) => cell.innerHTML = keywords[index]);
    return grid;
}
const table = document.body.appendChild(drawBoard(ROW, COL));




Aucun commentaire:

Enregistrer un commentaire