lundi 23 avril 2018

How can I use switch instead of multiple if statements?

I was wondering if it is possible to rewrite multiple if statements into a switch.

The problem is that a switch runs:

  1. all code after a case passes a check. Which is why the case statement runs all code after the first case.

    let arr = [1, 3];
    
    if( arr.includes(1) === true ) {
      console.log('if 1');
    }
    if( arr.includes(2) === true) {
      console.log('if 2');
    }
    if( arr.includes(3) === true) {
      console.log('if 3');
    }
    
    
    switch( true ){
      case arr.includes(1):
        console.log('switch 1');
      case arr.includes(2): 
        console.log('switch 2');
      case arr.includes(3): 
        console.log('switch 3');
    }
    
    1. if a switch has breaks in every case, it runs a single case, that passes the test.
let arr = [1, 3];

if( arr.includes(1) === true ) {
  console.log('if 1');
}
if( arr.includes(2) === true) {
  console.log('if 2');
}
if( arr.includes(3) === true) {
  console.log('if 3');
}


switch( true ){
  case arr.includes(1):
    console.log('switch 1');
    break;
  case arr.includes(2): 
    console.log('switch 2');
    break;
  case arr.includes(3): 
    console.log('switch 3');
    break;
}

So the question is: How can I rewrite multiple if statements into a single switch statement?

If I can't: Is there another more elegant syntax than the multiple if statements, that makes it apparent that I am making similar comparisons?

Aucun commentaire:

Enregistrer un commentaire