Command "switch" enters falls into "default"

Asked

Viewed 127 times

1

For any value you enter, the result is always "None of the alternatives", where the error is?

Follows the code:

<body>
  <p>Clique para exibir...</p>
  <!-- <button onclick="myFunction()">Clique aqui</button> -->
  <button onclick="myFunction()">Clique aqui...</button>

  <script>
  function myFunction()  {
    var x=prompt("Digite o mes:");
    mes=x;
    switch (mes) {
      case 1:
        alert("janeiro");
        break;
      case 2:
        alert("Fevereiro");
        break;
      case 3:
        alert("março");
        break;
      case 4:
        alert("abril");
        break;
      case 5:
        alert("maio");
        break;
      default:
        alert("Nenhuma das alternativas")
    }
  }
  </script>
</body>
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

The main problem is that it is not converting data entry which is always a string to a number which is what is comparing.

Eventually I could do that with the array instead of doing a huge switch.

switch (parseInt(prompt("Digite o mes:"))) {
case 1:
    alert("janeiro");
    break;
case 2:
    alert("Fevereiro");
    break;
case 3:
    alert("março");
    break;
case 4:
    alert("abril");
    break;
case 5:
    alert("maio");
    break;
  default:
    alert("Nenhuma das alternativas")
}

I put in the Github for future reference.

Documentation of parseInt().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.