要从嵌套数组中获取真实条件(数组),现在函数 returns 布尔值 true

To get a truthy condition(array) from a nested array, for now the function returns boolean value true

checkWin 函数 return 当作为索引号的数组在另一个数组的索引上有指定符号时为真。如何从嵌套的 winConditions 数组中检索结果为 true 的“cond”(数组)?

使用点击事件侦听器填充符号。

预期的结果应该是,如果 .some(cond) 变为真,那么 return 例如,那个条件。如果符号“X”出现在 [0, 1, 2] 上,则 return 这个数组

let testArray = Array(9).fill("") 
 
  const winConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  let xValue = "X";
  let oValue = "O";

function checkWin(value, array) {
    return winConditions.some((cond) =>
        cond.every((index) => array[index] == value));
}

console.log(checkWin(xValue, testArray));
console.log(checkWin(oValue, testArray));

您可以使用 .find() 而不是 .some(),这将 return .every() 回调 return 的第一个数组 true为了。您可以使用此数组来确定特定玩家是否获胜:

const testArray = Array(9).fill("");
testArray[3] = testArray[4] = testArray[5] = "O"; // test winning position
const winConditions = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

const xValue = "X";
const oValue = "O";

function getWinPos(value, array) {
  return winConditions.find((cond) =>
    cond.every((index) => array[index] == value)
  );
}

const xWinPos = getWinPos(xValue, testArray);
const oWinPos = getWinPos(oValue, testArray);

if(xWinPos) { // found a winning position row/col/diag for "X"
  console.log(xWinPos);
} else if(oWinPos) { // found a winning row/col/diag for "O"
  console.log(oWinPos);
}