My question divide in three questions:
1.Is it even possible ?
2.If yes can we do it with the default value ?
3.Or could with do it outside the switch statement ?
Example for questions 2:
switch(stuff) {
case 'something':
some event;
break;
case 'the case that could be add by the default element':
some event that could happen only after the code was executed
default:
magic code that would add another case element
}
Example for question 3:
switch(stuff) {
case 'something':
some event;
break;
case 'the case that could be add by the magic code':
some event that could happen only after the code was executed
default:
some default event
}
magic code that would be executed after the switch and that would add a case
You can't really code JavaScript so that it will modify itself, but you can code a switch statement such that certain cases will be ignored initially and then "turned on" later:
var enableCase = false;
switch(true) {
case stuff === 'something':
// some code;
break;
case enableCase && stuff === 'the case not initially enabled':
// some code
break;
default:
// turn on previous case:
enableCase = true;
break;
}
Having said that, I don't really recommend doing it. There is almost certainly a more sensible way to implement this depending on the underlying problem you are trying to solve. Perhaps with an if/if else/else block that tests a flag set elsewhere.
Related
In this action I am trying to say...
if VS_WRNG is Blank and if VS_WRNG is DSC or DSQ then set the two items
but when I click on VS_WRNG in my web app and select DSC it didn't autofill the BOB_TYPE answer with LIN.
Did I screw up the code or is it the ! not working like that and do I need to do a switch (true) & case (VS_WRNG != "")?
//Set BoB Type [TEMPORARY]
switch (!VS_WRNG) {
case "":
switch (VS_WRNG) {
case "DSC":
case "DSQ":
switch (VS_BTYP) {
case "":
setValue('BOB_TYPE',"LIN");
VS_BTYP = "LIN";
break;
}
break;
}
break;
}
Thanks
The primary issue you're having is that !VS_WRNG always results in a boolean. It can never result in an empty string "". So the case "": will never run. But even if it did, your code still won't work:
In this action I am trying to say... if VS_WRNG is Blank and if VS_WRNG is DSC or DSQ then set the two items
VS_WRNG cannot be simultaneously Blank and DSC or DSQ. You need to rethink your logic - the requirements are incompatible right now and quite illogical.
This is also quite an abuse of switch statements. If your switch statement has one case, it's an if statement. Just use an if statement like this:
if(VS_WRNG === "") { ... }
Your middle switch statement can be implemented also with an if statement, since you've written it to just check for two conditions:
if(VS_WRNG == "DSC" || VS_WRNG == "DSQ") { ... }
So I´m trying to compare a character stored within an object with the four cardinal points but it ain´t working. In this case, this.position.orientation value is E, but it jumps directly to the default option. I think it must be something related to trying to compare an array that is part of an object bu I have no idea how to solve it. Any help would be highly appreciated.
NOTE: the this.position.orientation was filled using previously using array.split(' ');, and it always stores just one character
switch (this.position.orientation) {
case 'N':
this.position.orientation = 'E';
break;
case 'S':
this.position.orientation = 'W';
break;
case 'E':
this.position.orientation = 'S';
break;
case 'W':
this.position.orientation = 'N';
break;
default:
break;
}
This is not a question, basically, check what is this.position.orientation before entering the switch statement and you´ll realise what the problem is about.
My Suggestion is check the DataType of this.position.orientation to make sure that its an String.
I am not sure, but you are doing comparison with char. Try to use case "E" instead case 'E'.
Try use ToString() command in this.position.orientation before compare.
If it comes from an Array, make sure that it isnt an array with only one position doing this.position.orientation[0] in switch clause.
I have a script in my project that will generate notifications, though, these notifications thus far have the same title and description through their pre-defined variables:
notificationTitle: "Notification",
notificationDescription: "This is a notification.",
This is rather boring, really. And whilst I can go and set the amount of notifications* I want the script to generate, along with enough case statements to facilitate them, this is not reasonable. In the environment where we intend to have multiple different notifications for multiple different users, I don't want to have to write a case statement for each one, like so:
function setNotificationDescription(iteration) {
"use strict";
switch (iteration) {
case 1:
values.notificationDescription = "One";
break;
case 2:
values.notificationDescription = "Two";
break;
case 3:
values.notificationDescription = "Three";
break;
case 4:
values.notificationDescription = "Four";
break;
case 5:
values.notificationDescription = "Five";
break;
case 6:
values.notificationDescription = "Six";
break;
default:
values.notificationDescription = "Seven";
}
}
*This would be filled by a count of objects in a JSON file in the future, but for my example I set it myself.
Live Example: http://moonsquads.com/scriptbase/notification-generation/
Is there a way to generate these case statements automatically?
Instead of setting the values.notificationDescription inside the function, I have moved it outside for demonstration purposes (compare the "case-version" with the "array-version"):
https://jsfiddle.net/6j98sxue/1/
This avoids switch-cases by using an array since numeric index is concerned, and avoids a big change to your original code.
In addition to the above, I would suggest a Code Review post and people there would give detailed comments on refactoring the existing code. Modifying the value object and getting values from it will cause problem, e.g. it is hard to test the code as we cannot do dependency injection.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm trying to figure out how I can streamline a possible long if else statement.
There are 8 possibilities that can be chosen and for each option 1-8 I want to display a message.
For example this is what works but I know can be writtern much better:
if(this.cv == '1'){
console.log('Greater Then 1');
} else
if(this.cv == '2'){
console.log('Greater Than 2');
}
etc...
Looking for something a little more dynamic.
Use a map:
var messages = {
'1' : 'Greater than 1',
'2' : 'Greater than 2',
....etc
}
console.log(messages[this.cv]);
If that is the exact format of your message (for all cases), then you could simply write:
console.log('Greater Than ' + this.cv);
However, if you need more flexibility with each case, then you can use a switch statement as other answers have suggested.
Use a switch statement:
switch(this.cv)
{
case '1':
console.log('Greater Than 1');
break;
case '2':
console.log('Greater Than 2');
break;
default:
//executed if no matches are found
}
Or a map would work also work well per adeneo's answer, since that is essentially how a switch statement is implemented. Both are good options for compressing several if-statements.
This is what the switch statement was made for.
switch(this.cv) {
case '1':
console.log("Greater than 1");
break;
case '2':
console.log("Greater than 2");
break;
}
You can even add a "catch-all" default action:
default:
console.log("I don't know what to do with "+this.cv);
switch(n)
{
case '1':
execute code block 1
break;
case '2':
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
You can use a switch statement , check this link for more details
Genaral Syntax of SWITCH:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
case labelN:
statementsN
[break;]
default:
statements_def
[break;]
}
In your case :
switch(this.cv) {
case '1':
console.log("Greater than 1");
break;
case '2':
console.log("Greater than 2");
break;
}
I'd say create an object that maps the possible values to messages and simply retrieve the message from the map like so:
var messages = {'1': 'Greater Then 1',
'2': 'Greater Than 2'};
console.log(messages[this.cv]);
depends sometimes i have many functions to add to various variables ..
in that case i prefer to use something like that.
i create an object with the answers. then i check if the answer exists and execute it.
i prefer that over switch
var a={'2':'greater than 2','1':'greater than 1'}
console.log(a[this.cv]?a[this.cv]:'')
another way to write this is
var a={'2':'greater than 2','1':'greater than 1'}
!a[this.cv]||(console.log(a[this.cv]));
or if you just have to do a short check i use javascript shorthand.
console.log('Greater then '+(a=this.cv,a==1)?1:(a==2)?2:'whatever');
or
console.log('Greater then '+(this.cv==1?1:2));
and in your case a
console.log('Greater than '+this.cv);
should be enough.
I'm new to writing switch statements after learning about it yesterday.
For some reason, this isn't working.
checkCase(2);
checkCase(1);
checkCase(0);
function checkCase(priorityType){
switch(priorityType){
case 2:
print(priorityType);
break;
case 1:
print(priorityType);
break;
case 0:
print(priorityType);
break;
}
}
The 'alert(2)' is triggered, 1 and 0 are not.
I've reversed the case 2: with case 1: and run the code again and 2 is once again triggered, 1 is not.
I've also tried adding break; and continue; to the cases, but still nothing.
Why is that? what have I done wrong?
----------------------EDIT---------------------------
Lots of responses saying that I need to add 'break;' which I've now done to each line.
Still no output. I've also changed 'alert' to 'print'. No difference.
-------------edit2-----------------------
my bad, the 'break' is working now. not sure what was going on when I checked last. Maybe needed to restart ff.
You must break; after each case.
function checkCase(priorityType){
switch(priorityType){
case 2:
alert(priorityType);
break;
case 1:
alert(priorityType);
break;
case 0:
alert(priorityType);
break;
//my two cents
default:
alert("No intended code for"+priorityType);
}
}
checkCase(2);
checkCase(1);
checkCase(0);
Two problems: Debugging using alert is problematic and you need break statements.
Try adding breaks and using print in the square free shell, and I think you'll see the proper result.
checkCase(2);
checkCase(1);
checkCase(0);
function checkCase(priorityType){
switch(priorityType){
case 2:
print(priorityType); break;
case 1:
print(priorityType); break;
case 0:
print(priorityType); break;
}
}
Because there are no break statements, once a matched case is found, it and the subsequent cases will fire.
So when you do:
checkCase(2);
You'll get:
alert(2);
alert(2);
alert(2);
When you do:
checkCase(1);
You'll get:
alert(1);
alert(1);
When you do:
checkCase(0);
You'll get:
alert(0);
If you were hoping to get:
alert(2);
alert(1);
alert(0);
You'd need to change your switch to include break; statements.
function checkCase(priorityType){
switch(priorityType){
case 2:
alert(priorityType);
break;
case 1:
alert(priorityType);
break;
case 0:
alert(priorityType);
break;
}
}