how to put a switch in a variable in javascript? - javascript

I'm making a little mini game and I have to put multiple switches inside of themselves, so I really need to know how to put a switch into a few words so I can make this game. I have tried it so that it's fully written out but it takes FOREVER and it is very confusing as to what is what. please help!
EDIT: im sorry i made this so confusing... let me say that again in english (: what i need to do is make it so when they either choose one of the cases or if they choose none of them (default) it would reactivate the switch. the way the person would choose is through a prompt. so what i thought i could do was make a switch into a variable then use that variable inside the switch basicly creating an endless thing that if they choose default it asks them again. here is an example i will post it in one minute
here you go!:
//this is the variable holding the switch
/*I I I I I*/
/*V V V V V*/
var switch1 = {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch(choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
switch1
break;
default:
//this will repeat it too
switch1
break; }
}
So how would i do this and make java accept this #ajaysinghdav10d?

JavaScript allows you to nest switch statements.
Have a look at this dummy example in which a service returns the location of the customer and his choice of product. Based on the combination of Choice and Location, a function to return the co-ordinates of the nearest store is called; I have used dummy values where ever necessary and alerts to explain the flow of control within the nested switch statements:
var choice = "CHO2"; /* call getChoice() function returning values from {CHO1, CHO2, ...}*/
var location = "LOC1"; /*call getLocality() function returning values from {LOC1, LOC2, ...}*/
switch (location) {
case "LOC1":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC1() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC1");
break;
case "CHO2":
alert("redirectToCHO2ofLOC1");
break;
default:
alert("redirectToRegret");
break;
}
break;
case "LOC2":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC2() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC2");
break;
case "CHO2":
alert("redirectToCHO1ofLOC2");
redirectToCHO2ofLOC2();
break;
default:
alert("redirectToRegret");
break;
}
break;
default:
alert("redirectToRegret");
break;
}
Updated answer based on the new context :
You must use recursion for that matter. Put your switch inside a function and call that function from the case statement of your switch, please have a look at this:
function recursiveSwitch() {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch (choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
recursiveSwitch();
break;
default:
//this will repeat it too
recursiveSwitch();
break;
}
}
Now just call the recursiveSwitch function from where ever you want and an endless loop would start.

Related

Switch with SINGLE case or if else

I am working on a enormous project and WebStorm inspections always offer me to transform switch constructions with single case or case + default, like this
switch (fieldInfo.Type()) {
case this.TYPE_NESTED:
changedFieldInfo.addFieldFromPrototype(proto)
break;
default:
changedFieldInfo._fieldInfo[this.FI_FIELDS] = [];
break;
}
to if else construction like this
if (fieldInfo.Type() === this.TYPE_NESTED) {
changedFieldInfo.addFieldFromPrototype(proto);
} else {
changedFieldInfo._fieldInfo[this.FI_FIELDS] = [];
}
My colleagues say that switch is more readable even if it has only one case clause, especially when checking for enumerations like TYPE in snippets above.
What does js community think about that?
Also assume that we are not going to add second case clause and to go back to a single clause very often, so maintenance issues are minor.
And one more question, is it possible to transform switch with break inside the case clause to if without using extra code, eg
switch (fieldInfo.Type()) {
case this.TYPE_NESTED:
if(smthIsTrue)
break;
changedFieldInfo.addFieldFromPrototype(proto)
break;
default:
changedFieldInfo._fieldInfo[this.FI_FIELDS] = [];
break;
}

Dynamic Switch in Javascript

I want to do a switch with dynamic content in javascript, I will put an example:
switch(terrain) {
case "Plains":
terrain = Plains.create(newPosition);
break;
case "Mountains":
terrain = ImpassableMountain.create(newPosition);
break;
case "Hills":
terrain = Hills.create(newPosition);
break;
case "Forest":
terrain = Forest.create(newPosition);
break;
case "River":
terrain = River.create(newPosition);
break;
default:
};
So if I want to add a new Terrain for example Ocean, I want that will be updated automatically. I am thinking about to put all the terrains in a array
var terrainArray = ["Plains","Mountains","Hills","Forest","River","Ocean",...]
But I don't know how to put that in a switch in the most optimized way because if I try
for(var i=0;i<terrainArray.length;i++){
if(terrain==terrainArray[i]){
Terrain.create(newPosition);
}
}
It wouldn't be optimized because it will go through the entire array.
Also I need to put the class dynamically so if that terrain is Plains I need to put Plains.create instead of other, maybe can I do that with an array of classes?
Use an object literal - that makes it much easier and faster as you don't have to loop the array everytime you lookup something. It's also easier to handle dynamically than a switch
const foo = {
Plains: Plains,
Mountains: ImpassableMountains
}
let x = 'Plains';
foo[x].create(newPosition)
You can simply use .indexOf to check if it's in that array and perform actions accordingly.
terrainArray.indexOf(terrain) >=0 ? Terrain.create(newPosition) : null;
To
it will go through the entire array., To find something in array it will.. always

Jump case in Switch statement in (javascript) (updated )

I want to ask about switch case statement in javascript.
switch(ch){
case 0:
//do something, if condition match ,so go to case 2 and 3 (no need to go case 1)
//if not match, go to case 1, 2, and 3
break;
case 1:
//..
break;
case 2:
//..
break
case 3:
//...
}
In my code has 4 cases . There is a condition in case 0 that will skip case 1 and go to case 2. How can I do that?
The switch statement is an alternative to long if else statements (See the docs here). In your case, I believe that you should use the regular if statements.
// check if it passes case1
if (condition === case1) {
// check if it passes case1
if (condition === case2) {
// check if it passes case1
if (condition === case3) {
// do something here...
}
}
}
You may also use ternary operator, although it might be a bit hard to read as you add more conditions.
i think if else statement better suit your requirement. if you still want to do it in switch here's example :) :
var sw = function(cs){
switch(cs){
case 1:
console.log("case 1 !!!");
sw(3);
break;
case 2:
console.log("case 2 !!!");
break;
case 3:
console.log("case 3 !!!");
break;
}
};
sw(1);
I believe this's what you are looking for:
function Switcher(choice){
switch(choice){
case 1: console.log(1);;
case 4: console.log(4); break;
case 2: console.log(2); break;
case 3: console.log(3); break;
}
}
and then call Switcher(1) and see the O/P
I was looking at some logic related to switches in JavaScript today, the code I was looking at used a series of if and else statements however there were a bunch of shared logic cases which could be consolidated.
Additionally if and else statements are not exactly equal to switch statements because the runtime may implement them with jump tables making the order of execution faster than if and else.
Because you can only continue iteration patterns in ECMAScript you can hack up a solution which looks like jumping by encapsulating the logic in a fake loop like so:
(function(){
//In some function use this code
var test = 2;
Switch: while(true) switch(test){
case 2: test = 1; continue Switch;
case 1: test = 0; continue Switch;
default:alert(test);return;
};
//End code example
})();
The condition for while(true) can be changed to use another variable for state if you need to.
This gets the code as close to using jump tables as you can in other languages and a similar pattern can implement things like goto or duffs device
See also How can I use goto in Javascript?
Or Porting duff's device from C to JavaScript
Or this GIST https://gist.github.com/shibukawa/315765020c34f4543665

Javascript Switch Case Not Working in socialengine

I am feeling a bit embarrassed to ask this silly question but somehow the following code is not working. The values (bed,room,floor) are fetched right but switch case not working.But the same snippet of switch case code works well in jsfiddle.I m sure I m missing something silly.I m using this in socialengine with mootools enabled
I also want to know how to get an element which has id=roomtype and which is inside a div whose class=form-elements but id=roomtype is not direct child of div class=form-elements.
I can get it by $$('.form-elements #roomtype').get('value') but this refers all elements with #roomtype, this $('.form-elements #roomtype').get('value') doesnt work
<script type="text/javascript">
var updatePrice=function()
{
var room= $$('.form-elements #roomtype').get('value') ;
// alert (room) gets AirCon or Dorm
var price;
switch (room)
{
case "AirCon":
price="10000"; alert("AirCon");
break;
case 'Dorm':
price="5000"; alert("Dorm");
break;
default:
price="00";
}
}
en4.core.runonce.add(updatePrice);// this add this function to DOM Ready
</script>
#1
ID's must be unique.
In MooTools you can do $('roomtype') to get the element with the ID roomtype.
You can also use document.id('roomtype') or even $$('#roomtype').
Since ID's must be unique it's irrelevant the parent of that element, because there is only one.
#2
Note that $ and $$ are different element methods in mootools. $$ takes a CSS selector and returns a collection/array.
$$('#roomtype').get('value'); // returns ['the value']
$('roomtype').get('value'); // return 'the value'
#3
The other problem I see is that you define the price inside the scope of updatePrice() function, so doing price = 5000 inside the switch will not leave the function's scope anyway. You might want to define the var price outside the function, or make the function return that value lie this:
// ...
switch (room) {
case "AirCon":
price = "10000";
alert("AirCon");
break;
case 'Dorm':
price = "5000";
alert("Dorm");
break;
default:
price = "00";
}
return price; // here
}
If you update your fiddle with HTML it will be easier to help you more.
P.s: You are always welcome to ask questions. No need to feel embarrassed.

Changing page content in a switch statement using more than 1 variable in the switch parameter. Can that be done?

The situation I have is a drop down list and an image on a html page. I'm using javascript script. I'm using a switch statement. I've constructed my switch and case statements. So far I got an alert box for each case that displays a unique message in the browser when I make a selection in the drop down list. But I want the image on the page to change with each message. I tried using multiple variables in the switch parameter but that disables the alert boxes. Is there a way for me to use a single switch variable that can call the message boxes and the images? Or is there a way to use multiple variables in the switch parameter? I've been researching the internet, even this forum for answers, but haven't found anything that matches my problem. I found some answers using if statements and AJax but that is outside of the scope of my homework and what we've learned so far. So basically my task is to use a switch construct to evaluate the selection and when a match is found, display the appropriate image and the alert box. Any suggestions.
It doesn't sound like you need multiple variables in the switch expression. Rather, you need multiple statements in each branch of your switch. For example:
switch(selectedValue)
{
case 'foo':
alert('foo');
imageElement.src = 'http://foo';
break;
case 'bar':
alert('bar');
imageElement.src = 'http://bar';
break;
}
You can change the source of the image for each case. Switch statements only accept one parameter.
HTML
<img src="image_path" id="myImage" />
JavaScript
var img = document.getElementById( "myImage" );
switch( value ) {
case 0:
alert( "message" );
img.src = "new_path";
break;
case 1:
alert( "message" );
img.src = "new_path";
break;
default: break;
}

Categories

Resources