[英]I'm trying to make sense of the React TicTacToe tutorial. How does their calculateWinner helper function operate?
First of all this is not a dupe of React tutorial function calculateWinner(squares) don't understand . 首先,这不是对React教程功能的computeWinner(squares)不了解的伪装 。
Looking at https://reactjs.org/tutorial/tutorial.html#declaring-a-winner : 查看https://reactjs.org/tutorial/tutorial.html#declaring-a-winner :
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++){
const[a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]){
return squares[a];
}
}
return null;
}
What does const[a, b, c] = lines[i];
const[a, b, c] = lines[i];
do? 做? What are squares[a],squares[b] and squares[c]?
什么是方格[a],方格[b]和方格[c]? I understand that the lines array contains all of the combinations of square positions that result in a win, but I can't understand how they are being defined and compared and the tutorial really doesn't offer any explanation, just "Here's a helper function that'll make it all work."
我知道lines数组包含导致获胜的所有正方形位置组合,但是我不明白它们是如何定义和比较的,并且本教程实际上没有提供任何解释,只是“这是一个辅助函数这样就可以了。”
lines[i]
refers to one of eight combinations of three values ( [0, 1, 2]
, [3, 4, 5]
, etc.). lines[i]
表示三个值( [0, 1, 2]
, [3, 4, 5]
等)的八个组合之一。 const[a, b, c] = lines[i];
assigns those three values to the variables a
, b
, and c
. 将这三个值分配给变量
a
, b
和c
。 This makes the condition in the following if
statement a lot more concise, as those three variables are used as indices to the squares
array. 这使得下面的
if
语句中的条件更加简洁,因为这三个变量用作squares
数组的索引。
const[a, b, c] = lines[i];
is equivalent to 相当于
const a = lines[i][0];
const b = lines[i][1];
const c = lines[i][2];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Tic-tac-toe code https://codepen.io/gaearon/pen/LyyXgK?editors=0010 井字代码https://codepen.io/gaearon/pen/LyyXgK?editors=0010
squares
are the slice
of squares
from the grid squares
是来自网格的squares
slice
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.