Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop returns both if and else outputs

I’m trying to make a Simon says game and the problem is inside my answerCheck function. I have it set to be called when both the generated pattern and the user pattern length are equal to 4 and to pass in the user pattern as currentLevel.

The problem is that no matter what the input of the user pattern is the function logs both correct and incorrect as well as running the code inside both statements.

const pattern = [4];

function answerCheck(currentLevel) {
  for (let i = 0; i < currentLevel.length; i++) {
    if (currentLevel[i] === pattern[i]) {
      console.log("success");
      // setTimeout(nextSequence(), 2000)
    } else if (currentLevel[i] !== pattern[i]) {
      console.log("incorrect");
      // var wrong = new Audio("./sounds/wrong.mp3");
      // wrong.play();
      $("body").addClass("game-over");
      /*
      setTimeout(function() {
        $("body").removeClass("game-over");
      }, 300);
      */
    }
  }
}

answerCheck([4]);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are a few ways to compare simple arrays (see this question), here is one:

const pattern = [4,3,2,1];

function answerCheck(currentLevel) {
  let success = currentLevel.length === pattern.length && currentLevel.every((el, i) => pattern[i] === el);
  
  if (success) {
      console.log("success");
  } else {
      console.log("incorrect");
  }
}

answerCheck([4]);
answerCheck([4,1,1,1]);
answerCheck([4,3,2,1,0]);
answerCheck([4,3,2,1]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading