检查3个值是否与If语句相同

时间:2017-11-28 23:36:57

标签: javascript if-statement

我正在构建一个Tic Tac Toe游戏,我想知道这种语法是否有效。似乎程序有时运行正常,有时不是这样,我希望你的意见。

int f(int* as) {
    *as = read(STDIN_FILENO, as, sizeof(int));
} //i print 123

int s;
f(&s);

printf("%d",s); // prints 4

所以基本上我在一个数组中检查位置0,1,2,如果它们具有相同的值(“x”或“o”)。这种语法是否正确?

**编辑

对于任何想要在这里看到完整项目的人来说。 https://codepen.io/Ispaxan/pen/ZaRjZW?editors=0001

4 个答案:

答案 0 :(得分:4)

你的意思是相同的价值。所以你需要检查的第一件事是3项同样的。

当3个值相等时,您只需检查其中一个值是userDraw还是compDraw并完成。

通过这种方式。您可以使if语句运行得更快,因为当第一个或第二个条件失败时,javascript引擎不会检查剩余条件。

if (spacesArray[0] === spacesArray[1] &&
    spacesArray[0] === spacesArray[2] &&
    (spacesArray[0] === userDraw || spacesArray[0] === compDraw) )

编辑:我正在检查Codepen并注意到了。如果你检查spacesArray[0] === (userDraw || compDraw),这将是一个错误。因为(userDraw || compDraw)将始终返回userDraw。

答案 1 :(得分:1)

我认为当你单独放置spacesArray[0]时,它会检查它是真还是假。

您可能想尝试:

if ( (spacesArray[0] == (userDraw || compDraw) && spacesArray[1] == (userDraw || compDraw) && spacesArray[2] == (userDraw || compDraw))){ }

答案 2 :(得分:1)

我会对userDrawcompDraw进行单独检查,以便了解谁赢了。另外,对于javascript古怪的平等原因,请使用===代替==

// destructure array
const [a, b, c] = spacesArray;

// check if a is not null or undefined
// check if a and b are equal
// check if a and c are equal
if (a && a === b && a === c) {
  // all 3 are the same value      

  // check if userDraw wins
  if (a === userDraw) {
    console.log(`${userDraw} wins`;
  }

  // check if compDraw wins
  if (a === compDraw) {
    console.log(`${compDraw} wins`;
  } 
}

**阐述为什么||在这种情况下不会起作用。 **

设定:

const userDraw = 'x';
const compDraw = 'y';
const spacesArray = ['y', 'y', 'y'];

// (userDraw || compDraw) will be 'x'

案例:

if (spacesArray[0] &&
  spacesArray[1] &&
  spacesArray[2] == (userDraw || compDraw)

这里失败了:

if ('y' && // -> true
  'y' && // -> true
  'y' === 'x') // -> false

案例:

if (spacesArray[0] === spacesArray[1] &&
  spacesArray[0] === spacesArray[2] &&
  spacesArray[0] === (userDraw || compDraw))

这里失败了:

spacesArray[0] === spacesArray[1] // 'y' === 'y' -> true
spacesArray[0] === spacesArray[2] // 'y' === 'y' -> true
spacesArray[0] === (userDraw || compDraw) // 'y' === 'x' -> false

答案 3 :(得分:0)

首先验证答案之间的相等性,最后验证答案是否为O或X

if ( spacesArray[0] == spacesArray[1] &&
    spacesArray[0] == spacesArray[2] &&
    spacesArray[0] == (userDraw || compDraw))
相关问题