Reputation: 43
I'm working on a MineSweeper program, and here's my problem:
So I make a 10x10 grid full of MineSquare objects which I defined earlier.
var grid = [];
for (var i=0; i<10; i++){
grid.push([]);
for (var j=0; j<10; j++){
grid[i].push(new MineSquare())
}
}
Then I make an array "bomb_list" to create 20 unique locations where the bombs will be.
var bomb_list = [];
var found;
var rand;
while (bomb_list.length < 20){
found = false;
rand = Math.floor(Math.random() * 100);
for (var i=0; i<bomb_list.length; i++){
if (bomb_list[i] === rand){found=true; break;}
}
if(!found){
bomb_list.push(rand);
}
}
Then I try to change the value of those MineSquare's to indicate they are bombs.
for(var x in bomb_list){
grid[ x / 10 ][ x % 10 ].touching = -1;
}
I am getting an error that says "Uncaught TypeError: Cannot read property '1' of undefined" which I believe is being caused when I try to take grid[x / 10].
Any reason why this is occuring?
Upvotes: 0
Views: 46
Reputation: 76
X/10
will give you a float value, should use Math.ceil
or Math.floor
to get the nearest int as per your logic. Then it should work.
Upvotes: 1
Reputation: 10372
x/10
will produce a float. When x
is 1
, it will be 0.1
. There is no index in grid
of 0.1
, so the result is undefined
. That is why you get that error.
You can Math.floor
or parseInt
depending on what you are trying to do:
for(var x in bomb_list){
grid[ parseInt(x / 10) ][ x % 10 ].touching = -1;
}
Upvotes: 1