试图了解此代码以匹配游戏项目的存储卡

时间:2018-11-27 01:05:15

标签: javascript function

这是来自https://medium.freecodecamp.org/vanilla-javascript-tutorial-build-a-memory-game-in-30-minutes-e542c4447eae

的免费代码阵营

我正在尝试自己创建一个类似的游戏,但是自从我迷上JS以来,这一直是一个惊喜。我无法理解这部分代码对于...是必需的,或者我想大致理解它!该网站说,这建立了匹配的逻辑,但是如果有人可以更好地分解它,我将不胜感激!如果您访问该站点,对我来说,checkForMatch函数是可管理的。我知道 !使事情布尔,也???将它们从true切换为false还是根据默认情况将其切换为其他方式?我也不记得我是否一次遇到了两个变量的声明,这意味着什么。

谢谢您的帮助!已经好几个小时了,我想我一天都碰壁了!

以下是网站的说明:

”“现在我们有了翻转卡,让我们来处理匹配逻辑。 当我们单击第一张卡片时,它需要等待直到另一张卡片被翻转。变量hasFlippedCard和flippedCard将管理翻转状态。如果没有翻转的卡片,则hasFlippedCard设置为true,而flippedCard设置为单击的卡片。我们还要切换切换方法以添加:“

    const cards = document.querySelectorAll('.memory-card');

    let hasFlippedCard = false;
    let firstCard, secondCard;

    function flipCard() {
      this.classList.add('flip');

      if (!hasFlippedCard) {
         hasFlippedCard = true;
         firstCard = this;
         return;
         }

         secondCard = this;
         hasFlippedCard = false;

         checkForMatch();
       }

1 个答案:

答案 0 :(得分:1)

对于您在“!”上的提问,这意味着不可以。你可以用它来 检查某些东西是true还是false,或者变量是否为null或包含值。我添加了一些评论,将在下面对此进行解释。

var test = null;
var theBool = true;
if(!test){ // if test is null or false
 // You will enter this if statement because test is null
}
if(!theBool){ // if theBool is null or false
 // You will not enter this if statement because theBool is 
// true.
}

test = 10;

if(!test){ // if test is null or false
 // You will not enter this if statement now because test is 
 // not null, it has the value of 10.
}

theBool = false;

if(!theBool){ // if theBool is false or null
// You will enter this if statement because theBool is false.
}

我还在您提供的代码块中添加了一些注释。

 // Grabbing everything with a class .memory-card
const cards = document.querySelectorAll('.memory-card');

let hasFlippedCard = false;
let firstCard, secondCard; 
/*
  same as 
  var firstCard;
  var secondCard;
*/

function flipCard() {

  // Adds the css class flip to what you just clicked on.
  this.classList.add('flip');

  // if hasFlipped === false or is null
  if (!hasFlippedCard) {

     // Set has flipped to true
     hasFlippedCard = true;

     // the first card value now = what you have clicked on.
     firstCard = this;

     // Function complete, return and wait for the next click
     return; 
     }

     // First card was set before, currently it is true, so 
     // the if statement was skipped.
     // The second card is now what you clicked on.
     secondCard = this;

    // Setting to false so next time you click, you will be
    // setting the firstCard value again.
     hasFlippedCard = false;

     // Both card values have been set, now check if they are
     // the same as each other.
     checkForMatch();
   }

享受JavaScript:)