即使使用slice(),JavaScript数组的大小在改组后也加倍

时间:2018-10-10 14:32:53

标签: javascript random html-table

我有一个5个单词的数组,我想将它们随机放置在HTML表的一部分上。当我运行下面的代码时,关键字会随机出现在表格中,但它们的数量会翻倍(我在网格上总共得到10个单词)。我不确定为什么用slice克隆不起作用。我是JS的新手,尚不了解其所有技术知识。对于我可能在做错的任何反馈,我们将不胜感激。

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));

1 个答案:

答案 0 :(得分:0)

您是否有可能两次致电drawBoard?执行代码时,我只有5个条目(下面的代码段)

var ROW = 8;
var COL = 8;

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));
<table id='grid'></table>