[英]Why is this array undefined in React?
我有以下代碼,用於在掃雷游戲中設置地雷,但我在 plantMines() function 中不斷收到錯誤,“TypeError: data[randomx] is undefined”。 我是 React 的新手,所以也許我錯過了一些簡單的東西,但我就是看不出問題出在哪里。
initBoardData(height, width, mines) {
let data = this.createEmptyArray(height, width);
data = this.plantMines(data, height, width, mines);
return data;
}
// Create array of grid
createEmptyArray(height, width) {
let data = [];
for (let i = 0; i < height; i++) {
data.push([]);
for (let j = 0; j < width; j++) {
data[i][j] = {
x: i,
y: j,
isMine: false,
neighbour: 0,
isRevealed: false,
isEmpty: false,
isFlagged: false
};
}
}
return data;
}
// Place mines on board
plantMines(data, height, width, mines) {
let randomx, randomy, minesPlanted = 0;
while (minesPlanted < mines) {
randomx = this.getRandomNumber(width);
randomy = this.getRandomNumber(height);
if (!(data[randomx][randomy].isMine)) { //--ERROR ON THIS LINE
data[randomx][randomy].isMine = true;
minesPlanted++;
}
}
return (data);
}
getRandomNumber(dimension) {
return Math.floor((Math.random() * 1000) + 1 % dimension);
}
編輯:codesandbox - https://codesandbox.io/s/minesweeper-luono?file=/src/Board.js
您在 getRandomNumber 中有錯誤 - 缺少括號:
getRandomNumber(dimension) {
return Math.floor(((Math.random() * 1000) + 1) % dimension);
}
不過還有一個問題,請使用@dellink 提出的解決方案:
randomx = this.getRandomNumber(height);
randomy = this.getRandomNumber(width);
你必須同時做出改變,所以它開始工作了!!
我解決了這個問題。 height
和width
沒有正確定義,因此randomx
和randomy
被視為字符串,而不是數字,因此數組定義錯誤。
您試圖不存在數組的索引。 因此; 你得到undefined
的錯誤。 您可以使用下面或@Enchew 的答案。
getRandomNumber(dimension) {
return Math.floor(Math.random() * Math.floor(dimension));
}
嘗試以這種方式改變
randomx = this.getRandomNumber(height);
randomy = this.getRandomNumber(width);
根據您的代碼,您應該訪問您的數組,例如: data[randomy][randomx]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.