youtube-tutorials
youtube-tutorials copied to clipboard
TypeError: randpos is undefined
I am getting "TypeError: randpos is undefined on line 72" and I don't know how to fix it :(
var randpos = empty[Math.round(Math.random()*(empty.length - 1))];
grid.set(FRUIT, randpos.x, randpos.y);
Can anyone help me?
How do you put things in the empty array? The error is probably up a bit in the code where you add positions to the empty array, something like empty.push({x:x, y:y}). If it isn't would you mind post the code from your complete setFood() function?
Here you go:
function setFood() {
var empty = [];
for (var x = 0; x < grid.width; x++) {
for (var y = 0; y < grid.height; y++) {
if (grid.get(x, y) === EMPTY) {
empty.push({x:x, y:y});
}
}
}
var randpos = empty[Math.round(Math.random()*(empty.length - 1))];
grid.set(FRUIT, randpos.x, randpos.y);
}
Just wanted to say thanks for helping me :)
I had the same issue and solved it by tracking the issue with console.log() entries at different parts of the code to see what the values of variables were at certain stages, and also which parts got executed or not. It turned out in my case that the iteration in setFood() didn't go through the "y-iteration" because I had misspelled a variable in the grid object. Instead of this.height I wrote this.heigt, which prevented the iteration condition in setFood() from being true, which in turn prevented empty from getting any values, which made it undefined.
var grid = {
width: null,
height: null,
_grid: null,
init: function(d, c, r) {
this.width = c;
this.heigt = r;
this._grid = [];
for (var x=0; x < c; x++) {
this._grid.push([]);
for (var y=0; y< r; y++) {
this._grid[x].push(d);
}
}
},