Error in code using switch and new date

3

I tried to do a function that returns the day of the week we are, via switch in JS, but somehow, the result does not appear. I debugged all the code but did not find the error.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> treinando js e switch</title>
</head>
<body>
     <p id="demo"> </p>


    <script>
    var day;
       function dia(){
        switch (new Date().getDay()) {
            case 0:
               day = "Segunda";
               break;
             case 1:
               day = "Terça";
               break;
             case 2:
               day = "Quarta" ;
               break;
             case 3:
               day = "Quinta";
               break;
             case 4:
               day = "Sexta";
               break;
             case 5:
               day = "Sabado";
               break;
             case 6:
               day = "Domingo";
                break;
         };
    document.getElementById('demo').innerHTLM = "hoje é "   + day;

    }


    </script>
</body>
</html>

Where am I going wrong?

    
asked by anonymous 14.12.2016 / 22:55

2 answers

3

The main mistake is that 0 is Sunday, then comes the other days. The beginning was a bit confusing too, the variable day was declared out of function for no apparent reason. This type of function doing all this is not the coolest way to do it though it works.

function dia() {
    var day;
    switch (new Date().getDay()) {
      case 0:
        day = "Domingo";
        break;
      case 1:
        day = "Segunda";
        break;
      case 2:
        day = "Terça";
        break;
      case 3:
        day = "Quarta" ;
        break;
      case 4:
        day = "Quinta";
        break;
      case 5:
        day = "Sexta";
        break;
      case 6:
        day = "Sábado";
        break;
    };
    console.log("hoje é " + day); //mudei para facilitar o teste
}
dia();

This can get better:

    function diaDaSemanaHoje() {
        return ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"][new Date().getDay()];
    }
    console.log("Hoje é " + diaDaSemanaHoje());
    
14.12.2016 / 23:02
-1

See if it helps:

var arrDay = ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"];

console.log("Hoje é " + arrDay[new Date().getDay()]);
    
15.12.2016 / 23:05