2 回答

TA貢獻1834條經驗 獲得超8個贊
您可以使用從 中獲得的值進行遞歸調用getAdjacentCells。但是,請確保getAdjacentCells只為相同的id. 現在,當您重復相同的調用時,效率非常低。
另請參閱代碼中的其他一些建議。
function isCellEmpty(adjacentCells) {
// I would move this check here, although not necessary if you prefer it in the loop.
if (typeof adjacentCells === "number") {
$("#" + id).empty().append("<div>"); // You can chain jQuery...
return;
}
for (let id of adjacentCells) { // Just use a for..of loop
if (id === null) continue; // keep IF-ELSE nesting flat.
let cell = board[getBoardPosition(id)];
if (cell.opened) continue; // Add this to avoid circling around
cell.opened = true;
isCellEmpty(getAdjacentCells(id)); // recursive call
}
}
對象值
您在代碼的注釋中寫道:
getAdjacentCells() 將返回類似于函數作為參數的對象數組或整數
但是,您在此答案下方的評論似乎表明情況并非(總是)。它可能是一個簡單的對象,可以解釋你為什么Object.values要迭代它。如果是這種情況,我會敦促進行更改,getAdjacentCells以便它確實返回一個數組。或者,如果這是不可能的,那么Object.values像你已經做過的那樣使用:
function isCellEmpty(adjacentCells) {
// I would move this check here, although not necessary if you prefer it in the loop.
if (typeof adjacentCells === "number") {
$("#" + id).empty().append("<div>"); // You can chain jQuery...
return;
}
for (let id of Object.values(adjacentCells)) { // Just use a for..of loop
if (id === null) continue; // keep IF-ELSE nesting flat.
let cell = board[getBoardPosition(id)];
if (cell.opened) continue; // Add this to avoid circling around
cell.opened = true;
isCellEmpty(getAdjacentCells(id)); // recursive call
}
}

TA貢獻2080條經驗 獲得超4個贊
遞歸在這里應該可以正常工作:在最基本的情況下,您可以使用id2. 但是,假設getAdjacentCells可能會返回您已經訪問過的單元格,除非您能夠跟蹤已訪問過的 ID 并將其傳入,否則您最終將無限遞歸。
function setCellState(id, visited) {
if(id === null) {
return;
}
if(visited === undefined) {
visited = new Set();
}
if(visited.has(id)) {
return;
}
visited.add(id);
board[getBoardPosition(id)].opened = true;
// getAdjacentCells() will return either an array of objects similar to the one the function takes as an argument or an integer
let adjacentCells = getAdjacentCells(id);
// if getAdjacentCells(id) returns a number, add a div to the HTML element with that id
if (typeof (adjacentCells) === "number") {
// Removes all other divs, this prevents repetition
$("#" + id).empty()
// Appends an empty div
.append("<div></div>");
} else if (typeof (adjacentCells) === "object") {
Object.values(adjacentCells).forEach(id2 => setCellState(id2, visited));
}
我冒昧地更改了方法名稱,以便更能代表該方法的實際作用。我還更改了它以從單個單元格的 ID 開始,因為這簡化了遞歸并允許圍繞 的行為進行注釋getAdjacentCells以提供更好的上下文。
添加回答
舉報