【发布时间】:2018-12-20 01:53:52
【问题描述】:
我正在创建一个 tictactoe 游戏,并尝试将 winPattern 2d 数组中的每个集合数组与 placePieces 数组进行比较。
我已经创建了循环来遍历每个 placePieces 数组的 winPattern 二维数组,但是因为它不会将每个数组识别为一个集合,而是简单地遍历各个值,所以它不能按预期工作。
const winPattern = [
//horizontal
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
//vertical
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
//diagonal
[0, 4, 8],
[2, 4, 6]
];
//positions that o or x would be in tictactoe
const placePieces = [0, 1, 2, 4, 8];
let count = 0;
nextPiece:
for (let i = 0; i < placePieces.length; i++) {
for (let j = 0; j < winPattern.length; j++) {
for (let n = 0; n < winPattern[0].length; n++) {
if (placePieces[i] === winPattern[j][n]) {
//Prints out the matches and mismatches
console.log(`It matches: Piece: ${placePieces[i]} //\\ Pattern: ${winPattern[j][n]}`);
continue nextPiece;
} else {
console.log(`It doesn't match: Piece: ${placePieces[i]} //\\Pattern: ${winPattern[j][n]}`);
}
}
}
}
我希望 placePieces 数组将值与 winPattern 2d 数组中的每个 SET 数组进行比较。
【问题讨论】:
-
提示: 您可以使用数组函数在一行中检查,如下所示:
let winCheck = winPattern.some(pat => pat.every(pos => placePieces.includes(pos)));仅检查winPatterns中是否存在模式pat其所有元素都包含在placePieces中。减少头痛!
标签: javascript arrays for-loop multidimensional-array tic-tac-toe