到目前为止,我只能在每个 if 语句之后硬编码相同的代码段,只需要更改 getAdjacentCells(id) 的参数即可。我一直无法找到重复这部分的方法。我认为这可以递归完成,但我不知道该怎么做。
编辑:我最初输入 isCellEmpty 得到了一个对象数组:[{topLeft: null}, {topCenter: "cell-1-2"}, {topRight: "cell-1-3"}, {middleLeft: null}, {middleRight: "cell-2-3"}],当实际上是单个对象时:{topLeft: null, topCenter: "cell-1-2", topRight: "cell-1-3", middleLeft: null , middleRight: "cell-2-3"}
// Gets an object that looks like this: {topLeft: null, topCenter: "cell-1-2", topRight: "cell-1-3", middleLeft: null, middleRight: "cell-2-3"}
function isCellEmpty(adjacentCells) {
Object.values(adjacentCells).forEach(id => {
// Checks that the ids in stored in the object values do not equal null
if (id !== null) {
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
// if getAdjacentCells(id) returns a number, add a div to the HTML element with that id
if (typeof (getAdjacentCells(id)) === "number") {
// Removes all other divs, this prevents repetition
$("#" + id).empty();
// Appends an empty div
$("#" + id).append("<div></div>");
// HERE'S WHERE IT STARTS: If getAdjacentCells(id) returns an object, do the same as above with every id in it
} else if (typeof (getAdjacentCells(id)) === "object") {
Object.values(getAdjacentCells(id)).forEach(id2 => {
if (id2 !== null) {
board[getBoardPosition(id2)].opened = true;
if (typeof (getAdjacentCells(id2)) === "number") {
$("#" + id2).empty();
$("#" + id2).append("<div></div>");
// HERE IT REPEATS:
} else if (typeof (getAdjacentCells(id2)) === "object") {
...
}
}
})
}
}
});
}
MMMHUHU
犯罪嫌疑人X
相关分类