Skip to content Skip to sidebar Skip to footer

Javascript Arrays Giving Nan

I have a bit of HTML that is supposed to bounce ball(s) around the canvas, but the arrays storing the coordinates seem to be 'NaN' when I set them to a random position and test wit

Solution 1:

You call this line

cirX[i] = Math.floor(Math.random()*width);

when width is still undefined. So you can only get NaN as a result.

To properly call the moveBall function from setInterval, you may use

(function(i) { // embedds i to protect its value (so that it isn't the one of end of loopsetInterval(function(){moveBall(i)}, 10);
})(i);

Solution 2:

It is because width is undefined when the statement gets executed for the first time. You can get the canvas and its dimension in the beginning and keep it global.

http://jsbin.com/agavoq/9/edit

To call setInterval you can use a self invoking function preserving the value of i

(function(x){
  setInterval(moveBall,10, x);
})(i);

Or simply

setInterval(moveBall,10, i);

Or

setInterval('moveBall(' + i+ ')',10);

Solution 3:

I see another issue because look at this line

setInterval('moveBall(i)',10);

The i is not what you think it is. You should not use a string in setTimeout.

Post a Comment for "Javascript Arrays Giving Nan"