[英]Error in Javascript while trying to access element from array
I'm working on a MineSweeper program, and here's my problem: 我正在开发MineSweeper程序,这是我的问题:
So I make a 10x10 grid full of MineSquare objects which I defined earlier. 因此,我制作了一个10x10的网格,其中充满了我之前定义的MineSquare对象。
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. 然后,我创建一个数组“ bomb_list”以创建炸弹所在的20个唯一位置。
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. 然后,我尝试更改那些MineSquare的价值,以表明它们是炸弹。
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]. 我收到一个错误消息,提示“未捕获的TypeError:无法读取未定义的属性'1'”,我认为是在尝试获取grid [x / 10]时引起的。
Any reason why this is occuring? 为什么会这样呢?
X/10
will give you a float value, should use Math.ceil
or Math.floor
to get the nearest int as per your logic. X/10
将为您提供一个浮点值,应根据您的逻辑使用Math.ceil
或Math.floor
来获取最接近的整数。 Then it should work. 然后它应该工作。
x/10
will produce a float. x/10
将产生一个浮点数。 When x
is 1
, it will be 0.1
. 当
x
为1
,它将为0.1
。 There is no index in grid
of 0.1
, so the result is undefined
. 0.1
grid
中没有索引,因此结果undefined
。 That is why you get that error. 这就是为什么您会收到该错误。
You can Math.floor
or parseInt
depending on what you are trying to do: 您可以根据要执行的操作使用
Math.floor
或parseInt
:
for(var x in bomb_list){
grid[ parseInt(x / 10) ][ x % 10 ].touching = -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.