简体   繁体   English

React教程功能calculateWinner(平方)不明白

[英]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 我有这个问题,请在React教程页面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? 在原始代码中有多余的平方[a]有什么好处?

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. 如果没有在if条件的开始处设置squares[a] ,则在未定义squares[a]情况下会出现js错误。

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. 它将首先检查a变量,如果未定义,则之后将不执行。

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. 检查squares [a]是否不为null,未定义,0,空字符串''和false,以便进一步检查squares [a]。 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. 如果squares [a]为null或undefined或false或0,则条件将返回false,并且由于“ &&”条件运算符,将不会进行进一步的检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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