javascript switch(true) - javascript

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'

Related

How to get out of an infinite prompt loop when the prompt is assigned to a variable

Here's my code
function cc() {
prompt("Choose Character")
}
function cs() {
var chars = setTimeout(function(){ cc() }, 3000);
switch (chars) {
case "spy":
selectedspy()
break;
case "bulovian soldier":
selectedbulovian()
break;
case "stonian soldier":
selectedstonian()
break;
default:
cs()
}
}
it keeps getting stuck in an infinite loop of asking the prompt again. I feel like I'm making a simple mistake, but I couldn't figure what I needed to type into google to get the answer
I believe this is what you are trying to do.
function cc() {
return prompt("Choose Character");
}
function cs() {
//This will only run the code once, if you wish to have a loop use setInterval()
setTimeout(function(){
var chars = cc();
switch (chars) {
case "spy":
selectedspy()
break;
case "bulovian soldier":
selectedbulovian()
break;
case "stonian soldier":
selectedstonian()
break;
default:
cs()
}
}, 3000);
}

Switch statement not behaving like it should

so i have a piece of code where i have an array (ar=[1,2,3,4,5]) and two functions. the functions are supposed to do the exact same thing: print out something if 1 exists in the array. but function func is always returning "nope" instead of "one" but function another always return the right thing. the only difference between the two functions is function func have a switch instead of an if/else. why? in the source code there are about 12 cases so i actually need to use the switch.
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (one) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}
function another (num) {
if(num===2){
console.log("found two");
} else if(num===3){
console.log("found thre");
} else{
console.log("nope");
}
}
ar.forEach(func);
ar.forEach(another);
You have to use the value you want to compare to one
hence
case 1:
instead of
case one===1
here's a fiddle
https://jsfiddle.net/cunx1ono/
Easiest way. Change the switch param to true if you want to use a comparison in the case, because one===1 returns true/false. This is why you always get "nope".
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (true) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}

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
}

Cannot read property 'done' of undefined due to switch

I have a function which gaining data by ajax. The problem is that construction switch causing this error:
cannot read property 'done' of undefined
I don't know why...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
function changeSelect(input,type)
{
var out;
switch(type)
{
case "sport" : out=$.post("/ajax/ajax.php",{sport:input.value});
case "competition" :out=$.post("/ajax/ajax.php",{competition.value});
}
out.done(function(data)
{
$("#output").html(data);
});
}</script>
Thanks for answer.
The likely cause of the error you are getting is that the value of type does not match either of your case statements. Thus, out remains undefined and gives you the error you see.
In addition, you must use break; statements in case of your case: statements and {competition.value} is not valid ES5 Javascript. Perhaps you want something like this:
function changeSelect(input, type) {
var out;
switch (type) {
case "sport":
out = $.post("/ajax/ajax.php", {sport: input.value});
break;
case "competition":
out = $.post("/ajax/ajax.php", {sport: competition.value});
break;
default:
break;
}
if (out) {
out.done(function(data) {
$("#output").html(data);
});
}
}
I don't know exactly what you meant with your {competition.value}. I guessed that maybe you wanted it to be {sport: competition.value}, but I don't see competition defined anywhere so I'm not really sure.
Or, perhaps remove some duplicate code and use this:
function changeSelect(input, type) {
var val;
switch (type) {
case "sport":
val = input.value;
break;
case "competition":
val = competition.value;
break;
default:
break;
}
if (val) {
$.post("/ajax/ajax.php", {sport: val}).then(function(data) {
$("#output").html(data);
});
}
}

switch between functions with checkboxes?

I'm trying to simplify some information on my play-site.
There are two dif. user-types, students and others.
Many places and stores offer a discount to students, and I would therefore make this accessible with a checkbox that changes some of the scripts.
This Is my example (simplifyed as good as i could):
<head>
<script TYPE="text/javascript" SRC="script/script_uteplasser.js"></script>
</head>
<body>
<form action="">
<input type="checkbox" id="checkbox_student" onclick="student();"><span>I'm A student!</span></input></form>
(...)
</body>
javascript (script_uteplasser):
//--------------------SAMFUNDET---------------------
samfundet = "...blablablabla..." + cc_samfundet() + "...blablablabla...";
//----INNGANGSAV. SAMFUNDET----
var checkbox1 = document.getElementById("checkbox_student");
function student(){
if (checkbox1.checked){
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "Free"; break; case 2: return "Free"; break; case 3: return "Free"; break; case 4: return "Free"; break; case 5: return "Free"; break; case 6: return "Free"; break; case 0: return "Free";}}
}
else{
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "100,-"; break; case 2: return "100,-"; break; case 3: return "100,-"; break; case 4: return "100,-"; break; case 5: return "100,-"; break; case 6: return "100,-"; break; case 0: return "100,-";}}
}
}
//-------------------------------------------------
This doesn't kill the script, but isn't returning any information either.
Why do you want to redefine function ?
You can check in your function if checkbox is checked. If you want really to redefine function use this code :
//declare your function :
function cc_samfundet () {
//...
}
//or :
var cc_samfundet2 = function () { /* ... */ };
//redefine your function :
cc_samfundet = function () {
//...
}
//or with an existing function :
cc_samfundet = cc_samfundet2;
It doesn't return anything because you're only defining your function(s) in your evaluation. If you add a second pair of parentheses afterwards, it should work how you intend.
That said, this is a really poor design pattern. First of you don't really need to make what you're doing functions here. Second is creating the same named function twice with completely separate logic - that pretty much brakes every good programming principle.
Update: Here is something to point you in the right direction,
var checkbox1 = document.getElementById("checkbox_student");
// Assuming this function should do something else too?
function student() {
cc_samfundet(checkbox1.checked);
}
var cc_samfundet = function (isStudent) {
var d = new Date();
var theDay = d.getDay();
switch (theDay) {
case 1:
return isStudent ? "Free" : "100,-";
// and so on
}
}

Categories

Resources