Javascript井字脚趾水平检查不工作(减less)

我正在做一个井字游戏,我得到了下面的代码:

let matrix = 3; let moves = [[2,2,2], [1,0,2], [1,0,1]]; let checkWinner = () => { let winner; // Horizontal Check for (let i = 0; i < matrix; i++) { winner = moves[i].reduce((a, b) => (a === b) ? a : 0); if (winner) return winner; } // Vertical Check for (let i = 0; i < matrix; i++) { winner = moves.reduce((a, b) => { return a[i] === b[i] ? a[i] : 0; }); if (winner) return winner; } } let winner = checkWinner(); if (winner) { console.log('player '+ winner + ' won the game'); } 

这里的水平检查工作,但垂直检查没有。 逻辑上,垂直检查的代码对我来说是有意义的,它应该可以工作。 我认为这与减lessfunction有关。

有人能告诉我垂直检查有什么问题,告诉我怎样才能使其工作

       

网上收集的解决方案 "Javascript井字脚趾水平检查不工作(减less)"

从传递给reduce的函数返回的值成为它的下一个第一个参数,所以你需要返回a而不是a[i]并检查if (winner[i])

 const winner = moves.reduce((a, b) => a[i] === b[i] ? a : [0, 0, 0]); if (winner[i]) return winner; 

通过将列转换成看起来像行的东西,并用一个函数执行两个检查,可能会更好:

 const lineWinner = line => line.reduce((a, b) => a === b ? a : 0); const checkWinner = () => { // Horizontal Check for (let i = 0; i < matrix; i++) { const line = moves[i]; const winner = lineWinner(line); if (winner) return winner; } // Vertical Check for (let i = 0; i < matrix; i++) { const line = moves.map(row => row[i]); const winner = lineWinner(line); if (winner) return winner; } }; 

既然它是方形的,那么你可以同时做两个,如果你想要的话:

 const lineWinner = line => line.reduce((a, b) => a === b ? a : 0); const column = i => moves.map(row => row[i]); const checkWinner = () => moves.reduce( (winner, row, i) => winner || lineWinner(row) || lineWinner(column(i)), 0);