JavaScript's switch
is fairly limited in what it can do, but that's not to say you can't get creative:
switch ([ var1, var2 ].join(',')) {
case '1,1':
alert("1");
break;
case '2,2':
alert("2");
break;
}
Here combining the two values with something like a comma means you have a single value you can then switch
on. The switch
itself can handle several different matches for the same branch, but the matches have to be very simple:
case '1,1':
case '1,2':
case '1,3':
// ...
break;
Where here any of those will follow the same branch.
If you're looking for something where either var1
or var2
can be a particular value, then it's time for an alternate approach using a look-up table:
let alerts = {
'1': '1',
'2': '2'
};
let var1 = 3;
let var2 = 2;
let hit = [ var1, var2 ].some(v => {
if (alerts[v]) {
alert(alerts[v]);
return true;
}
});
Here you can use some
to find the first matching value in your array of possible values to test.
Remember that within the context of switch
each condition is evaluated before the switching happens. It isn't evaluated like an if
is because switch
is meant to follow one branch and one branch only. if
chains necessarily go from one to the next until one triggers.