Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

285
Visualizações
Is there any mistake in comparing strings in JS?

I'm making tic tac toe game and I'm facing issue. If user's input is not equals to X or O then it should print the message Enter correct signs but I have no idea what's wrong in my code. Only else if's block is not working properly.

here is code of that function :

let p1, p2, s1, s2;

function startGame() {
  playAgain();
  p1 = document.getElementById("p1").value;
  p2 = document.getElementById("p2").value;
  s1 = document.getElementById("s1").value;
  s2 = document.getElementById("s2").value;

  if (p1 == "" || p2 == "" || s1 == "" || s2 == "") {
    alert("Enter the details.");
    playAgain();
  } else if (
    s1 != "X" ||
    s1 != "x" ||
    s1 != "O" ||
    s1 != "o" ||
    s2 != "X" ||
    s2 != "x" ||
    s2 != "O" ||
    s2 != "o"
  ) {
    alert("Enter correct signs.");
    playAgain();
  } else {
    alert("You can start the game." + p1 + s1 + p2 + s2);
    isStarted = true;
  }
}

Thank you :D

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Try to "and" your conditions instead of "oring" them.

else if (
   (s1 != "X" &&
    s1 != "x" &&
    s1 != "O" &&
    s1 != "o") ||
   (s2 != "X" &&
    s2 != "x" &&
    s2 != "O" &&
    s2 != "o")
  )

I personally would make use of every function to make it even shorter and less repetitive:

const validInputs = ["X", "x", "O", "o"]

else if (validInputs.every((item) => s1 !== item)
      || validInputs.every((item) => s2 !== item)) {
...
about 4 years ago · Santiago Trujillo Relatório

0

It seems line a logic error on the if statement, i tried this and it works properly

if (
    s1 != "X" &&
    s1 != "x" &&
    s1 != "O" &&
    s1 != "o" ||
    s2 != "X" &&
    s2 != "x" &&
    s2 != "O" &&
    s2 != "o"
  ) {

But you also need to validate that s1 isn't equal to s2 because the users can type something like s1='X', s2='x' and it would be valid

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda