I have a javascript function that loos like this :
var usedNums= new Array(76);
function setSquare(thisSquare)
{
var currSquare = "square"+ thisSquare;
var colPlace = new Array(0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4);
var colBasis = colPlace[thisSquare] * 15;
var newNum;
do{
newNum = colBasis + getNewNum() + 1;
}while(usedNums[newNum]); //UnCaught TypeError here
usedNums[newNum] = true;
document.getElementById(currSquare).innerHTML = newNum;
}
The error says:
Can not read property '5' of undefined.
I have checked using console.log statement and all the variables above are getting expected values .
I understand what Type Error is but not sure where is it breaking.
**Edit:**Here is the complete Script:
window.onload = new newCard;
var usedNums= new Array(76);
function newCard()
{
if(document.getElementById){
for(var i =0; i<24;i++)
{
console.log("Value of I is " + i);
setSquare(i);
}
}else{
alert("Sorry, your browser does not support this script");
}
}
function setSquare(thisSquare)
{
console.log("thissquare" + thisSquare);
var currSquare = "square"+ thisSquare;
console.log("currsquare" + currSquare);
var colPlace = new Array(0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4);
console.log("colplace" + colPlace);
var colBasis = colPlace[thisSquare] * 15;
console.log("colbasis"+ colBasis);
var newNum;
do{
newNum = colBasis + getNewNum() + 1;
console.log("new nUM" + newNum);
}while(usedNums[newNum]);
usedNums[newNum] = true;
document.getElementById(currSquare).innerHTML = newNum;
}
function getNewNum()
{
var a = Math.floor(Math.random() * 15);
console.log("random number" + a);
return a;
}
This line:
window.onload = new newCard;
is:
newCard
as a constructor (which it isn't) onload
Since you are invoking newCard
there, it runs before you reach the next line:
var usedNums= new Array(76);
So usedNums
is undefined when you try to read from it.
You need to assign the newCard
function as your load handler. So don't invoke it:
window.onload = newCard;
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.