3 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
對于初學者,您永遠不會將結(jié)果分配intiateGrid(10)給網(wǎng)格。應(yīng)該是let grid = intiateGrid(10)。代碼也有更多問題,但請讓我了解更多。例如應(yīng)該intiateGrid(number)創(chuàng)建一個方陣?初始值應(yīng)該是多少?此外,不要在循環(huán)時改變矩陣。
const grid = intiateGrid(10);
const player = {
rowIndex: 0,
colIndex: 0
}
//player starts at [0][0]
movePlayer(0, 0)
function intiateGrid(x) {
const arr = new Array(x).fill(0); // array with x zeros
const grid = arr.map(element => new Array(x).fill('O')) // array with x arrays, each with x zeros.
return grid;
}
function movePlayer(row, col) {
grid[row][col] = 'P';
//set -1 to previous location
grid[player.rowIndex][player.colIndex] = 'X'
//update player location
player.rowIndex = row;
player.colIndex = col;
console.log(`Player is at [${player.rowIndex}][${player.colIndex}]`)
}
movePlayer(1,0);
movePlayer(1,1);
movePlayer(1,2);
movePlayer(1,3);
movePlayer(2,3);
grid.forEach(row => console.log(row.join(' | ')))

TA貢獻1871條經(jīng)驗 獲得超8個贊
從您的問題中并不完全清楚,但是:
例如,let p = grid[0][0]然后我希望能夠?qū)⑵湟苿拥?grid[1][0]、grid[1][5] 等。
使您看起來好像要創(chuàng)建某種指向二維數(shù)組結(jié)構(gòu)中某個位置的“指針”。沒有真正的方法可以用一個簡單的值來實現(xiàn)這一點。一種方法是使用對象:
let p = { x: 0, y: 0 };
然后你可以創(chuàng)建函數(shù)來使用這樣的對象來返回一個網(wǎng)格單元:
function getCell(pointer) {
return grid[pointer.x][pointer.y];
}
function setCell(pointer, value) {
grid[pointer.x][pointer.y] = value;
}
除了像這兩個示例那樣將其隱藏在函數(shù)內(nèi)部之外,您最終無法避免使用兩個單獨的數(shù)字來顯式索引到二維結(jié)構(gòu)中。
添加回答
舉報