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

110
Visualizações
OR statement being ignored

I'm trying to fire my masterFunction only if certain keys are pressed. However it's being called regardless of what button is clicked. Even though the console log shows a different key.

Can anyone advise?

//Update display on keydown event
addEventListener('keydown', (e) => {
    pressedKey = event.key;
    console.log(pressedKey);
    keyDownOperatorMapping(e);
});

let keyDownOperatorMapping = (e) => {
if (pressedKey === "+" || "-" || "*" || "Enter" || "Backspace" || "." || "/") {
masterFunction(e);
} 
};

Example: https://jsfiddle.net/rykawgs9/

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It is because your current condition is

Hey is pressedKey equal is "+" or is "-" is true or //goes on

As string with length more than one is always one it always return true your condition is always true

So one way archive these

addEventListener('keydown', (e) => {
  pressedKey = event.key;
  console.log(pressedKey);
  keyDownOperatorMapping(e);
});

let keyDownOperatorMapping = (e) => {
  const keys = ["+", "-", "*", "Enter", "Backspace", ".", "/"]
  if (keys.includes(pressedKey)) {
    console.log("Found");
  }
};
about 4 years ago · Juan Pablo Isaza Relatório

0

You have to put the variable that you are comparing to. Which is in your case, the pressedKey:

if (pressedKey === "+" || pressedKey === "-" || pressedKey === "*" || pressedKey === "Enter" || pressedKey === "Backspace" || pressedKey === "." || pressedKey === "/")
...
about 4 years ago · Juan Pablo Isaza Relatório

0

You can reduce the code a little by adding the searchable keys to an array, and then check that the array includes the key that was entered.

const allowed = ['+', '-', '*', 'Enter', 'Backspace', ',', '/'];

document.addEventListener('keydown', (e) => {

  const { key } = e;

  if (allowed.includes(key)) {

    // masterFunction(e)
    console.log(key);

  }

});

Additional documentation

  • Destructuring assignment
about 4 years ago · Juan Pablo Isaza 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