Why Is My Switch Statement Running Multiple Cases?
I have the following function: $('#drpType').change(function () { var SelectedVal = this.value; switch (SelectedVal) { case '2021': console.log('a');
Solution 1:
It's because you don't have a break statement. Without it, the code will "fall through".
var x = 10;
switch (x) {
case 10:
console.log('With break');
break;
case 20:
console.log('I never run');
break;
}
console.log('-------');
switch (x) {
case 10:
console.log('Without');
case 20:
console.log('a break');
case 30:
console.log('it just');
case 40:
console.log('keeps going');
}
The reason this exists is because sometimes it's useful to fall through. You could imagine a case where you're updating the state of a game and what stuff to happen for a specific kind of enemy as well as for all enemies.
var characterType = 'big boss';
switch (characterType) {
case 'big boss':
console.log('Update the big boss');
case 'enemy':
console.log('The big boss is also an enemy so run the basic enemy code');
break;
case 'player':
console.log('The boss is not a player so we will not run this.');
break;
}
It's not incredibly common to utilize fall-through but it does have its use cases.
Finally, here's what your code should look like:
$("#drpType").change(function () {
var SelectedVal = this.value;
switch (SelectedVal) {
case "2021":
console.log('a');
console.log('b');
break; // <--
case "2020":
console.log('a');
break; // <--
case "ADB":
console.log('b');
break; // <--
case "PWP":
console.log('c');
break; // optional. It's visually consistent but doesn't do anything
}
}
Solution 2:
You are missing your break; statements on each of your cases:
$("#drpType").change(function () {
var SelectedVal = this.value;
switch (SelectedVal) {
case "2021":
console.log('a');
console.log('b');
break;
case "2020":
console.log('a');
break;
case "ADB":
console.log('b');
break;
case "PWP":
console.log('c');
break;
}
Post a Comment for "Why Is My Switch Statement Running Multiple Cases?"