I am trying to populate a table with randomly generated numbers from 1 to 15 with no repeats. The code I'm using just keeps displaying "undefined" in all the cells.I think the problem is with the random part but can't figure out why it's going wrong.
function setup()
{
cells = new Array([document.getElementById("cell00"),
document.getElementById("cell01"),
document.getElementById("cell02"),
document.getElementById("cell03")],
[document.getElementById("cell10"),
document.getElementById("cell11"),
document.getElementById("cell12"),
document.getElementById("cell13")],
[document.getElementById("cell20"),
document.getElementById("cell21"),
document.getElementById("cell22"),
document.getElementById("cell23")],
[document.getElementById("cell30"),
document.getElementById("cell31"),
document.getElementById("cell32"),
document.getElementById("cell33")]);
placeValues(cells);
}
function placeValues(cells)
{
var numbers = new Array();
var randomLoc;
var temp;
for (var i = 0; i < 16; i++)
{
randomLoc = Math.floor(Math.random() * 15 + 1);
temp = numbers[i];
numbers[i] = numbers[randomLoc];
numbers[randomLoc] = temp;
}
i = 0;
for (var rows = 0; rows<4; rows++)
{
for (var cols = 0; cols < 4; cols++)
{
if (numbers[i] !=0)
cells[rows][cols].innerHTML = numbers[i];
else
{
cells[rows][cols].innerHTML = "";
i++;
}
}
}
}
<html>
<head>
<script></script>
</head>
<body onload="setup()">
<div id="content">
<p>You can move any number into an empty spot by moving up, down,
right, or left. Diagonal moves are not allowed. The object is
to get all the numbers into correct order, from 1 through 15
with the empty space at the end.</p>
<table width="60%" align="center">
<tr>
<td height="60"><span id="cell00"></span></td>
<td><span id="cell01"></span></td>
<td><span id="cell02"></span></td>
<td><span id="cell03"></span></td>
</tr><tr>
<td height="60"><span id="cell10"></span></td>
<td><span id="cell11"></span></td>
<td><span id="cell12"></span></td>
<td><span id="cell13"></span></td>
</tr><tr>
<td height="60"><span id="cell20"></span></td>
<td><span id="cell21"></span></td>
<td><span id="cell22"></span></td>
<td><span id="cell23"></span></td>
</tr><tr>
<td height="60"><span id="cell30"></span></td>
<td><span id="cell31"></span></td>
<td><span id="cell32"></span></td>
<td><span id="cell33"></span></td>
</tr>
</table>
</div>
</body>
It displays "undefined" in all of the cells which tells me for some reason either the numbers array or the column of the cells array is not being populated. Could you help me out?