"Switch" command enters "default"

1

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

Follow 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>
    
asked by anonymous 05.08.2018 / 20:43

1 answer

1

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

You could eventually do this with array instead of making 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")
}

parseInt() documentation.

    
05.08.2018 / 20:50