简体   繁体   中英

React tutorial function calculateWinner(squares) don't understand

I have this problem understand this code in the react tutorial page 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;
}

This particular line

if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {

I don't understand why it can't be

if (squares[a] === squares[b] && squares[a] === squares[c]) {

What benefits are of having the extra squares[a] in the original code?

If you don't set the squares[a] in the begin of if condition, you can get the js error if squares[a] is not defined.

For simple, we have the condition like this:

if (a && a === b && a === c) {

it will check the a variable first, if it not defined, the after will not execute.

It is checked if squares[a] is not null, undefined, 0, empty string '' and false, so that further checks of squares[a] would be possible. If squares[a] is null or undefined or false or 0 then the condition would return false and further checks won't be done due to "&&" condtion operator.

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