Is it possible to have multiple switch cases in one switch case? - javascript

Is it possible to make like a two layer switch case? Say I have two expressions, that inside the the first case it looks for the second expression? I have googled but I have not found anything that I look for.
switch (Middle, Direction) {
case true:
case 'left':
code block
break;
case 'right':
code block
break;
break;
case false:
case 'left':
code block
break;
case 'right':
code block
break;
break;
default:
code block
}

Yes, you have to use individual, complete switches:
switch (Middle) {
case true:
switch (Direction) {
case 'left':
//code block
break;
case 'right':
//code block
break;
}
break;
case false:
switch (Direction) {
case 'left':
//code block
break;
case 'right':
//code block
break;
}
break;
default:
//code block
}
Note that in the above, if Direction isn't 'left' or 'right' but Middle is true or false (which, if it's really a boolean, it must be), then no default code is run as the subordinate switches don't have defaults.
Alternately, you might combine Middle and Direction, which makes it easier to use a default for non-matching cases:
switch (Middle+'|'+Direction) {
case 'true|left':
//code block
break;
case 'true|right':
//code block
break;
case 'false|left':
//code block
break;
case 'false|right':
//code block
break;
default:
//code block
}
Or look at a dispatch object:
var actions = {
"true|left": function() {
// code for Middle = true, Direction = left
},
"true|right": function() {
// code for Middle = true, Direction = right
},
"false|left": function() {
// code for Middle = false, Direction = left
},
"false|right": function() {
// code for Middle = false, Direction = right
},
"default": function() {
// code for the default
}
};
(actions[Middle+"|"+Direction] || actions.default)();
...though in this specific case it doesn't buy you much of anything over a switch.

Just use another switch in your case.

Related

Click event: switch statement not working

I´m trying to trigger multiple click events depending on the var clicked, however the switch statement isn´t working. I think it´s the "var" inside the Switch parameter but I have no idea how to correct it:
var buttonQ = document.getElementById('Heater1button');
var buttonW = document.getElementById('Heater2button');
var buttonE = document.getElementById('Heater3button');
var buttonA = document.getElementById('Heater4button');
var buttonS = document.getElementById('Heater6button');
var buttonD = document.getElementById('OpenHHbutton');
var buttonZ = document.getElementById('KicknHat');
var buttonX = document.getElementById("Kickbutton");
var buttonC = document.getElementById('CClosedHHbutton');
$(document).click(function() {
switch (var) {
case buttonQ:
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case buttonW:
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
case buttonE:
document.getElementById('E').play(), $("#displaytext").text("Heater 3")
break;
case buttonA:
document.getElementById('A').play(), $("#displaytext").text("Heater 4")
break;
case buttonS:
document.getElementById('S').play(), $("#displaytext").text("Heater 6")
break;
case buttonD:
document.getElementById('D').play(), $("#displaytext").text("Open HH")
break;
case buttonZ:
document.getElementById('Z').play(), $("#displaytext").text("KicknHat")
break;
case buttonX:
document.getElementById('X').play(), $("#displaytext").text("Kick")
break;
case buttonC:
document.getElementById('C').play(), $("#displaytext").text("Closed HH")
break;
}
})
You shouldn't use a switch statement, use event listeners attached to each element.
buttonQ.addEventListener("click", function() {
document.getElementById('Q').play(), $("#displaytext").text("Heater 1");
});
buttonW.addEventListener("click", function() {
document.getElementById('W').play(), $("#displaytext").text("Heater 2");
});
and so on for all the buttons.
Something like this?
$(document).click(function(e) {
var id = e.target.id;
switch (id) {
case "Heater1button":
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case "Heater2button":
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
}
});
You're correct, the issue is the var inside the switch statement. What variable does this refer to? A switch statement is used to "check the result of a and do one of x, y, etc". In your example I don't see any declaration of a value called "var" that the switch is using to evaluate what case to run.
In any event, even if you did have a variable somewhere else in your code called var, it won't work because that is a reserved word. You can't name a variable using the word you use to name variables.
You are switching on var, which itself does not appear to exist from the code you have provided. You need to know what was clicked, so you need to use what the jQuery .click() method provides - "this". Or perhaps in your case you should switch on $(this).attr("id").
See this: https://api.jquery.com/click/

Make specific case execute last in switch

I need to make a case execute at the last. Any ideas?
$.each(dataNames, function (varName, itemVal) {
switch (varName)
{
case "afshin":
alert('afshin');
break;
case "saeed":
alert('saeed');
break;
case "larry":
alert('larry');
break;
case "abc":
alert('abc');
break;
default:
alert('Default case');
break;
}
});
from the code above i need the case 'abc' to get executed at the last of all cases as i'm manipulating some code which has to execute from the other cases.
FYI, dataNames is a JSON object

Are there any possibilities to use "goto" inside switch statement in javascript?

This is my example program in JS. I have to iterate or loop inside the switch statement. So I have used goto, but it doesn't working.
Are there any other options to loop this or is my syntax wrong?
var input = 1;
switch (input)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
if (..) { }
else
{
goto case 2;
}
break;
default:
alert("No Return");
break;
}
Are there any possibilities to use "goto" inside switch statement in javascript?
No, there are no possibilities to use "goto" inside switch statement, or anywhere else, since JavaScript has no such statement.
To solve your problem, as suggested in a comment, organize your cases (moving 3 above 2) so you can use fall-through:
var input = 1;
switch (input)
{
case 1:
...
break;
case 3:
...
if (..) { ...; break; }
// fall through to case 2
case 2:
...
break;
default:
alert("No Return");
break;
}
In this case, make sure to comment the fall-through so people looking at your code don't think it's a bug. You may also need to add a hint so that your linter does not complain.
Or, just put the logic common to 2 and 3 in a little function:
function someLogicFor2Or3() { ... }
case 2:
someLogicFor2OrMaybe3();
break;
case 3:
...
if (..) { }
else someLogicFor2OrMaybe3();
break;
I have used the following technique to do this :
var input = 1;
while (1) {
switch (input) {
case 1:
...
break; // switch
case 2:
...
break; // switch
case 3:
...
if (..) { }
else {
input = 2; // goto case 2;
continue; // while
}
break; // switch
default:
alert ("No Return");
break; // switch
}
break; // while
}

javascript switch(true)

Hi i am trying to handle an ajax json response
here is my code
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
It works for me:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the case labels must be equal to true, not just implicitly true.
Also, only the first case that evaluates to true will execute.
SOLVED
Based on SLaks answer i modify the code as below
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
Thank to all
You need to read up on the switch statement. You should not be switching on a constant value.
It appears that you need to use if statements, as you don't really want to be switching on your j value:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
In a case like this, a better way to do this is probably something like:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}
Why not use an object literal instead of a switch(true) ?
const j= {
choice1: false,
choice2: true
};
const map = {
true: 'default',
...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']
console.log(map) // 'choice2'

Using || in javascript switches

Is this code possible?
switch (rule)
{
case 'email' || 'valid_email':
valid = this.validate_email(field);
break;
}
No, it is not possible, Switch statements doesn't do arithmetic calculus.
However, you can use case chaining or a bunch of if's:
switch (rule)
{
case 'email':
case 'valid_email':
valid = this.validate_email(field);
break;
}
Close, but this will work:
switch (rule)
{
case 'email':
case 'valid_email':
valid = this.validate_email(field);
break;
}
The reason why it works is that without a break;, execution continues within the switch block.

Categories

Resources