I found this example to make range work with switch statement:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26) && (value <= 50)):
result = ">= 26.";
break;
case ((value >= 1) && (value <= 25)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
But if I modify the code and remove the second check for the value the example will still work:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26)):
result = ">= 26 .";
break;
case ((value >= 1)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
So if I passed 29 even that I have two true cases the first one will be selected. My question is that how switch statement works in most of programming languages it will start comparing from the top or its only in this case (and is it good or bad to write it like that?).
switch statement checks for matches from top to bottom.
From MDN docs on switch statement:
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
I would do something like this (with if and else if chains):
function GetText(value) {
var result;
if (value == 0) {
result = "Equals Zero.";
} else if (value <= 25) {
result = "Between 1 and 25.";
} else if (value <= 50) {
result = "Between 26 and 50.";
}
return result;
}
Related
I am implementing a drag'n'drop interface in js which has two tables of objects and a single object as source or destination. To execute the "move" operation, I thought of using these two class methods:
_getVar(id) {
var ind;
switch (id[0]) {
case 'c':
return this.clipboard;
case 's':
ind = Number(id.substr(1)) - 1;
return this.SynthPatches[ind];
case 'f':
ind = Number(id.substr(1)) - 1;
return this.FilePatches[ind];
}
}
move(from, to) {
var fv = this._getVar(from);
var tv = this._getVar(to);
if (fv == undefined) return "Source empty";
if (tv == undefined) return "Destination undefined";
tv = fv;
return "Ok";
}
This does not work. fv and tv are local references to the correct objects. The reference fv is copied to tv and then both are forgotten.
I would like something like a deep copy in python, but it looks like the only solution is to inline _getVar() nine times, which makes for really ugly code.
The easiest way to reduce duplication here is probably to add an optional second parameter to the function and allow it to set as well as get, e.g.:
_getOrSetVar(id, value) {
var ind;
switch (id[0]) {
case 'c':
if (value !== undefined) this.clipboard = value
return this.clipboard;
break;
case 's':
ind = Number(id.substr(1)) - 1;
if (value !== undefined) this.SynthPatches[ind] = value
else return this.SynthPatches[ind];
break;
case 'f':
ind = Number(id.substr(1)) - 1;
if (value !== undefined) this.FilePatches[ind] = value
else return this.FilePatches[ind];
break;
}
}
And perform your update like this:
this._getOrSetVar(to, this._getOrSetVar(from))
// It is simple code
var num = prompt("put number");
// This way is not worked
switch (num) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
// But this worked
if (num > 0){
console.log(num++);
} else if (num < 0){
console.log(num -2);
}
My first way by "switch" is not worked but "if" method worked.
I tried all of thing for changing code or other ways but the same result.
Please guys help me.
Because the statement num > 0 inside you case will return true or false.
If you do this:
switch (true) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
It will work.
Cases cannot be expressions, you must normalize your input first.
Although it is valid to place an expression in a case, in this scenario a more tried-and-true way of dealing with this is to first normalize your input first.
You can determine direction for example:
var num = parseInt(prompt("put number"), 10);
var direction = num < 0 ? -1 : 1;
switch (direction) {
case 1:
console.log("num++");
break;
case -1:
console.log(num - 2);
break;
}
The switch acts as a case switcher, meaning you cannot make comparisons to create cases, just list cases by case, and perform some function from this case. The if / else structure is suitable for making comparisons, as the expected result in the if call is always a boolean.
Example:
const a = 1;
if (a === 1) {
console.log('hello');
} else {
console.log('sad');
switch (a) {
case 1 : console.log('hello'); break;
default: console.log('sad'); break;
In your case, I recommend using if/else if/else, as it is more recommended.
Is it possible to use nested switch statement in javascript.
My code is some what look like
switch(id1)
{
case 1:
switch(id2){
case 1:{
switch(id3){
case 1:{}
case 2:{}
}
}
case 2:{
switch(id4){
case 1:{}
case 2:{}
}
}
}
case 2:
}
If yes then it is a good practice to do or we can use any alternate approach.
Your approach is absolutely fine.
You can make the switch nesting less complex by using switch (true):
switch (true) {
case ((id1 === 1) && (id2 === 1) && (id3 === 1)) :
case ((id1 === 1) && (id2 === 1) && (id3 === 2)) :
case ((id1 === 1) && (id2 === 2) && (id3 === 1)) :
case ((id1 === 1) && (id2 === 2) && (id3 === 2)) :
case ((id1 === 2) && (id2 === 1) && (id3 === 1)) :
case ((id1 === 2) && (id2 === 1) && (id3 === 2)) :
case ((id1 === 2) && (id2 === 2) && (id3 === 1)) :
case ((id1 === 2) && (id2 === 2) && (id3 === 2)) :
}
Yes, you can use inner switch like this way,
Please check this demo : https://jsfiddle.net/1qsfropn/3/
var text;
var date = new Date()
switch (date.getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
switch(date.getFullYear()){
case 2015:
text = "It is Weekend of last Year.";
break;
case 2016:
text = "It is Weekend of this Year.";
break;
case 2017:
text = "It is Weekend of next Year.";
break;
default:
text = date.getDay();
break;
}
break;
}
document.getElementById("demo").innerHTML = text;`
You can use a nested switch statement but that can quickly become a spaghetti code and therefore it is not recommended. I would rather use functions with the nested switch statement for code clearance or maybe use recursive function depending on what the code is supposed to do.
This is only a pseudo-code but I hope it gives you some idea on how to implement it. You have to be carefull to make the recursion stop on some given value of the ID.
This pseudo-code increments the value of the ID by 1 if the value of the ID is 1, and increments by 2 if the value is 2. If the value is not 1 or 2 the recursion ends.
function recursiveSwitch(var id) {
switch(id) {
case 1:
recursiveSwitch(id + 1);
break;
case 2
recursiveSwitch(id + 2)
break;
default:
return;
}
}
Basically, it's possible but I think it depends on the complexity of the nesting if it's recommended to use nested switch statement or to use functions with the nested switch statement as Ómar Óskarsson has suggested.
I got a function that should return a result depending on a dealed Black Jack hand. I used a switch statement for this, eventhough I'm not sure you could use multiple switch in a function. Anyhow I got an error saying 'missing ; before statement' after the first 'result' text in the first 'case'. This code is what I have been taught so I'm not sure where I did go wrong. Could you please give me a hint or anything, please? Refards, Thomas.
function printResult(playResult, dealResult) {
var text = "";
switch(playResult) {
case (playResult == 21) : result "black jack";
break;
case (playResult > 21) : result "busted";
break;
case (playResult < 21) : result "safe";
break;
}
switch(dealResult) {
case (dealResult < 17) : result "safe";
break;
case (dealResult == 17 && < 21) : result "stop";
break;
case (dealResult == 21) : result "black jack";
break;
}
return result;
}
var result = "Player: " + playResult + ", Dealer: " + dealResult;
ANSWER = (printResult(5+9+10, 6+3+7));
Maybe you want result to be a variable assigment?
result = "black jack"
or maybe a return?
return "black jack"
It looks like you're trying to do "if logic" in the case statement; that's not how a switch works. A switch is going to take the value of dealResult and do a straight compare.
switch(dealResult)
{
case 21: //dealResult MUST be 21
result = 'blackjack!'
break;
case 20: //dealResult MUST be 20
//etc..
break;
case >20: //not valid, will break
}
As far as I know, if you need to do > and < compares, you should be using an if -> else block.
You have to remove all of the playResult variables inside of the switch block.
In addition, switch does not support higher than or lower than so a if is better suited for this situation.
function printResult(playResult, dealResult) {
var result;
if(playResult == 21) {
result = "black jack";
} else if(playResult > 21) {
result = "busted";
} else {
result = "safe";
}
if(dealResult < 17) {
result = "stop";
} else if(dealResult == 17 && dealResult < 21) {
result = "stop";
} else {
result = "black jack";
}
return result;
}
var result = "Player: " + playResult + ", Dealer: " + dealResult;
ANSWER = (printResult(5+9+10, 6+3+7));
This is a lot closer, but there is still problems with your logic.
Looking at your function, even if you get the switch working i don't think the logic is what you're aiming it to be.
If the purpose of the function is tell you who won the game, ergo the result as your name implies then you need to first put the rules down.. lets just for readability write it in pseudo..
Where either player has blackjack check the following
Player Blackjack to Dealer Blackjack = Push (Draw)
Player Blackjack to Dealer Anything = Player Win
Player Anything to Dealer Blackjack = Dealer Win
Then check if one is bust, to win a player must of held
Player > 21 = Dealer Win
Player <=21 and Dealer > 21 = Player Win
After that, we can do the simple checks.
Player == Dealer = Push
Player > Dealer = Player Win
Player < Dealer = Dealer Win
You can't really use a switch statement effectively to do this. You 'can' use it but for something like this, if else will suffice.
function blackJackWinnerIs(player, dealer)
{
if((player == 21) || (dealer==21))
{
if(player > dealer)
return "Player";
else if (player < dealer)
return "Dealer";
else
return "Push";
}
else if(player > 21)
return "Dealer";
else if(dealer > 21) // already checked if player<=21
return "Player";
else if(player > dealer)
return "Player";
else if(dealer > player)
return "Dealer";
else return "Push";
}
var hands = [
{player:21,dealer:21},
{player:20,dealer:21},
{player:21,dealer:17},
{player:22,dealer:17},
{player:17,dealer:22},
{player:19,dealer:18},
{player:18,dealer:20},
{player:20,dealer:20}
];
for(var i=0; i<hands.length;i++)
{
var winner = blackJackWinnerIs(hands[i].player,hands[i].dealer);
console.log("Player:",hands[i].player," Dealer:",hands[i].dealer," => Winner:",winner);
}
This is functional.. but it won't protect you from bad inputs e.g. if you accidentally passed in two nulls you would get a "push" result when really you should either send out an error or void the game... but thats all on you.
I'm writing swtich javascript switch statement in JS file and figured out the problem whole day still cannot find the solution.
Here is my javascript file written in jQuery :
var percent = 20;
var widthbytes;
switch(percent)
{
case 0:
widthbytes=0;
break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
average.width(widthbytes);
It always return to default instead of 30. Anything wrong with my codes ?
switch statement only check the value of variable and then give the result according to that value so your expression
case (percent > 10 && percent < 20):
return boolean value which is not not comparable to variable value. Use if-else to get the job done.
just make a bit change in your code.
You have switch(percent)**in your code, only change for this ***switch(true)*.
The reason for that is because the switch statement return a boolean value, this is why we need they have the same comparation, i.e. boolean vrs boolean.
For example the case 10: return one value; true or false.
I can't see a problems with #Carlos Marin's answer. This works:-
var percent = 10; //test values-> 10, 11, 19, 20, 21, 29, 30
var widthbytes;
switch(true){
// case 0:
// widthbytes=0;
// break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
console.log(widthbytes);
switch statements don't work like that. Your second case is checked like this: if (percent == (percent > 10 && percent < 20)) ..., which will not yield the desired result.
You could use an if / elseif / else construct:
if (percent === 0) {
widthbytes = 0;
} else if (percent > 10 && percent < 20 {
widthbytes = 16;
} else if (percent >= 20 && percent < 30 {
widthbytes = 30;
} else {
widthbytes = 0;
}
Or you could use a function that turns the ranges into constants:
function getRange(percent) {
return Math.floor(percent/10);
}
switch(getRange(percent)) {
case 10:
widthbytes = 16;
break;
case 20:
widthbytes = 30;
break;
default:
widthbytes = 0;
}
Note that to get a cleaner implementation i assimilated your original case 0: into the default, since they both do the same thing. If that is not desirable, you need to change the getRange function to no longer return the same range for 0 as for any number between 0 and 10.