Replace If/Else with Case javascript

Asked

Viewed 2,024 times

4

I would like to replace if/Else with Case because I believe it will be better for understanding the code since it will be a little long, but I cannot access the Array that will have the conditions to activate the actions. Error is in code or logic?

ex:

window.onscroll = function animaMenu() {
    var menu = [pageYOffset > 70 , pageYOffset > 800 ];
    switch (menu) {
        case 0:
            var x = document.getElementById("nav").className = "navegacao-movel"
        break
        case 1:
            var x = document.getElementById("ball").className = "movimento"
            alert("teste")
        break
    }
}
window.onload = animaMenu();

That code is what I intend to change

window.onscroll = function animaMenu() {
    if (pageYOffset > 70) {
          document.getElementById("nav").className = "navegacao-movel"

    } else if (pageYOffset > 800) {
          document.getElementById("nav").className = "navegacao"        

    } else if (pageYOffset > 1600) {
          document.getElementById("section").className = "hover"        
    }
}
window.onload = animaMenu();

5 answers

5


You’re making a switch in a list, I believe it only applies to a primitive value. Also, Javascript uses true and false for boolean values, no 0 and 1.

However, there is a way to put your conditions true/false in an array and make a switch in the first one that applies. The only detail is that, in your case, this has to be done backwards (because there is a hierarchy of conditions - if X > 800 then X > 70, then you have to test the bigger ones first).

var menu = [pageXOffset > 1600, pageXOffset > 800, pageXOffset > 70];
switch (menu.indexOf(true)) {
    case 0:
        var x = document.getElementById("nav").className = "hover"
    break
    case 1:
        var x = document.getElementById("nav").className = "movimento"
    break
    case 2:
        var x = document.getElementById("nav").className = "navegacao-movel"
    break
}

The function indexOf class Array takes the first index at which an element is found. If you then have an array of booleans, just look in this array for true.

  • I thought that using Number in the case of the example I would take the position of the Array and with that the condition calculation, I will test its response.

  • @Heltonss hm, I get it, but in fact that’s not how the switch works. But it might be possible to do something like what you want using a bitset library. I’ll do a quick search, if it works out I’ll come back here.

  • for sure the decision of if is better and cleaner, I believed that with case would leave more readable using array, but my time does not let me do a wider search, even so thank you.

  • 1

    @Heltonss I updated my answer. You can do this using a native Array.

  • Fantastic I knew I was not so crazy rsrs, but did not imagine the need of the indexof would not think of it so soon, Thanks again and it worked correctly. pg: is not pageXOffset is pageYOffset I think I was wrong when typing the question.

4

In your case, to facilitate understanding and decrease lines of code, it is not necessary switch(case) nor if&else, you can only use Array'as demonstrated in part of the @mgibsonbr(condition array), but I don’t see why to use it switch(case):

var values = ["navegacao-movel","navegacao","hover"];
var cond   = [pageYOffset > 1600, pageYOffset > 800, pageYOffset > 70];
document.getElementById("nav").className = values[cond.indexOf(true)];

This way you can even add more conditions and values if you want.

  • really the solution is also good, the fact of having chosen the case was to have a line of reasoning and follow it. but it was very good.

  • What do you mean, have a line of reasoning? you can’t get one this way? - I got the pageYOffset as you spoke in comment.

  • I’d really like to know why Downvote, Downvoter. What’s wrong with my answer?

  • 2

    +1 in this case where the code is homogeneous (only changes one value, but even if it changes two or three) this solution is better. Only in a heterogeneous case (e.g., where the code is radically different according to the condition) is it justified to use a switch.

2

When you put the else if you will have to put a new condition. For example:

   else if( x > y) { };

But in the last term, the last condition must be a else which corresponds to say that no previous conditions funtionou:. For example:

  if(x == y){
      // verficação 1
  }else if(x < y){
      // verficação 2
  }else if(x > y){
      // verficação 3
  }else{
      // Nenhuma das condições funcionou então ... 
  }

I hope I helped. Hug.

  • 2

    -1 In this case you should use the default:

  • 1

    I just showed an error in the code that doesn’t use the switch, but rather the if/else, so much so that the question was edited, but his observation in his point of view is correct.

2

Personally I don’t really like switch/case. Ugly syntax and easy to make mistakes. One option to be considered is to use an array. Follows a pseudocode (untested):

opcoes = {};
opcoes["1"] = function() { faz_isso(); };
opcoes["2"] = function() { faz_aquilo(); };
opcoes["3"] = function() { faz_outro(); };

opcao = "" + menu; // converter para string

if (menu in opcoes) {
   // executa opção
   opcoes[menu]();
} else {
   // equivalente ao "default:" do switch/case
}
  • The suggestion is good, but the way it is is not directly applicable to the OP code. Also there is no vector in your solution, only a common object.

  • @mgibsonbr Uma opção a ser considerada é usar um vetor. It can be considered, but not necessarily :P

  • @epx It’s very codex was looking for something more readable and easy to understand. even so grateful.

0

Taking into account that you want to change the value of this element document.getElementById("nav").className

I would use it this way:

document.getElementById("nav").className = (pageXOffset > 1600) ? "hover": ( (pageXOffset > 800)? "movimento":"navegacao-movel" );

Basically is a IF of a line and works as follows

CONDIÇÃO ? VERDADEIRO : FALSO

in the example I used 2

CONDIÇÃO ? VERDADEIRO : ( CONDIÇÃO ? VERDADEIRO : FALSO )
  • It does not fit the OP code, because you simply did not use the condition (PageXOffset > 70), and also, I believe that this solution, despite being made in only one line, is not easy to understand for those who look.

Browser other questions tagged

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