[英]Two Dimensional Array of Structures in JavaScript
我想在javascript中創建二維數組,其中每個單元格都是具有屬性的結構。 如何訪問單元結構的屬性?
// function to create cell objects
function cell () {
return {
"value" : 0,
"open" : 0,
"mine" : false
};
};
// initialise all cells
var game = new Array(10);
for(var i = 0 ; i < 10; i++){
game[i] = new Array(10);
for(var j = 0 ; j < 10; j++){
game[i][j] = cell();
}
}
如何訪問屬性?
我試過不同的命令,我得到未定義的屬性。
game[0][0]["mine"] = true;
game[0][0].mine = true;
謝謝。
----更新----我收到此錯誤
TypeError: Cannot set property 'mine' of undefined (line 38)
// Minesweeper game
// ask user to the size of game
var rows = Number(prompt("Please enter number of rows", "10"));
var cols = Number(prompt("Please enter number of columns", "10"));
// calculate number of mines
var mines = Math.floor(rows*cols*0.2);
// function to create cell objects
function cell (value, open) {
return {
"value" : value,
"open" : open,
"mine" : false
};
};
// initialise all cells
var game = new Array(rows);
for(var i = 0 ; i < rows ; i++){
game[i] = new Array(cols);
for(var j = 0 ; j < cols ; j++){
game[i][j] = cell(0, false);
}
}
// place mines randomly
for(var i = 0 ; i < mines ; i++){
var placedMine = false;
while(!placedMine){
var x = Math.floor((Math.random()*rows));
var y = Math.floor((Math.random()*cols));
if( game[i][j].mine === false){
game[i][j].mine = true;
placedMine = true;
}
}
}
問題不在於數組本身,而在於代碼中的最后一個if語句
if( game[i][j].mine === false){
game[i][j].mine = true;
placedMine = true;
}
j先前已定義並在for循環中使用。 當j
等於cols
並且j保留值( cols
的值)時,for循環退出,因此if語句中的條件等於
if( game[0][cols].mine === false){
...
}
並且由於您從未為game[0][cols]
分配任何內容,因此表達式( game[0][cols]
)是未定義的,並且沒有名為mine
屬性
您也有一個功能性錯誤。 您在最后一個for循環中使用i作為地雷的計數器以及行號。 我認為您真正想做的是
// place mines randomly
for(var i = 0 ; i < mines ; i++){
var placedMine = false;
while(!placedMine){
var row = Math.floor((Math.random()*rows)),
col = Math.floor((Math.random()*cols)),
cell = game[row][cell];
if(cell.mine === false){
cell.mine = true;
placedMine = true;
}
}
}
我進行了三處更改:
x
和y
更多的描述性名稱 cell
的新變量 row
和col
(以前是x
和y
)作為索引,而不是i
和j
通過創建一個變量來保存的單元格引用卸下的需要索引兩次和重命名x和y使代碼更容易閱讀(尤其是因為x通常為又名列號水平值和y通常是垂直的值)
更新:我不知道為什么我的答案被否決了,因為這是在OP發布更新之前發布的,但是無論如何。
我只是這樣做:
// function to create cell objects
function cell() {
return {
"value": 0,
"open": 0,
"mine": false
};
};
// initialise all cells
var game = new Array(10);
for (var i = 0; i < 10; i++) {
game[i] = new Array(10);
for (var j = 0; j < 10; j++) {
game[i][j] = cell();
}
}
console.log(game[0][0].mine);
然后我可以在控制台上正確獲得該值。 訪問它到底有什么問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.