简体   繁体   中英

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 .

Looking at 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]; do? What are squares[a],squares[b] and squares[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[i] refers to one of eight combinations of three values ( [0, 1, 2] , [3, 4, 5] , etc.). const[a, b, c] = lines[i]; assigns those three values to the variables a , b , and 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.

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

Tic-tac-toe code https://codepen.io/gaearon/pen/LyyXgK?editors=0010

squares are the slice of squares from the grid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM