简体   繁体   中英

Generate table using random subset of an array

Currently this script takes the words from the list and generates a grid, giving the words random positions each time. When the words are generated I want them to be split into individual characters, into cells next to each other - how do I do this?

  var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog", "log", "pan", "can",  "man", ];
  var shuffledWords = listOfWords.slice(0, 12);
  shuffledWords.sort(function() {
  return 0.5 - Math.random();
});

 var table = $('<table class="tablestyle">');
 var rows = 6;
 var cols = 2;
 var tr;
 var index;

for (var row = 0; row < rows; row++) {
tr = $('<tr>');
for (var col = 0; col < cols; col++) {
    index = (row * cols) + col;
    $('<td>').text(shuffledWords[index]).appendTo(tr);
}
tr.appendTo(table);
}

 table.appendTo('body');

 $('<table>' + innerTable + '</table>').appendTo('body');

Try sorting the list randomly before slicing it. Like this

listOfWords.sort(function() {
  return 0.5 - Math.random();
});
var shuffledWords = listOfWords.slice(0, 12);
<script type="text/javascript">
var html = "<table border='0' width='100%'>";
html += "<tr> <td> Search ID </td> <td> Name </td> <td>Location</> <td> Reason </td></tr>"
html += "<tr> <td> 1 </td> <td> Bob </td> <td>Glasgow</> <td> Hello </td></tr>"
html+="</table>";

$('#outputID').append(html);
</script>

Where it says

<td> Bob </td> 

replace it with

"<td>" + varibleName + "</td>"

And the varible name could be each character? Just put this in a loop that suits?

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM