Javascript switch wrong case - javascript

Hello (yet again) a question about javascript, this one has to be an easy one but I just can't see what I did wrong, I think something really stupid:
I have a textbox and a button. When i click the button the value wil be passed to a variable called activiteitn. Code:
activiteitn = $("#m2activiteitn").val();
It gets the value, so when I filled in the number 1, activiteitn = 1.
After that I have a switch that looks like this:
switch(activiteitn) {
case 1: activiteitn = 1.2;
break;
case 2: activiteitn = 1.375;
break;
case 3: activiteitn = 1.55;
break;
case 4: activiteitn = 1.725;
break;
case 5: activiteitn = 1.9;
break;
default: alert("hoi");
break;
}
The problem is that even if I fill in the number 1, it jumps to the default case, causing it to alert. If I place a alert at case 1 that alert does not show up. The first thing that came in my mind was that the activiteitn was not 1, so right after the switch I placed another alert:
alert (activiteitn);
Now, first what happends is I get the alert "hoi", then I get the second alert of activiteitn that says: 1. So after that I thought, "Maybe its a string", so I changed the cases to strings like: case "1" & case ("1") but that did not work either. The problem, it always goes to the default case and I can not figure out why that is, I hope someone sees what I did wrong and can help me out.

.val() returns a string, not a number. So after the line:
activiteitn = $("#m2activiteitn").val();
the variable activiteitn actually equals "1", not 1. Since case...switch uses strict equality, your test will always fail.
To fix, simply change the above line to:
activiteitn = +$("#m2activiteitn").val(); // convert to a number
or
activiteitn = parseInt($("#m2activiteitn").val(),10); // convert to an integer
or
activiteitn = parseFloat($("#m2activiteitn").val()); // convert to a float

Use parseInt(activiteitn, 10); to turn your String into an Integer. Switch-case statements in Javascript don't play nicely with Strings half the time.

Related

letting switch stmt run with no result, or checking the switch var type to not trigger it in the 1st place

I've made a chat bot for my uni group, which gives you schedule based on input msg. In bots logic there's a weekday var, which represents... well, the week day. But it could be both an int and a string, depending on user input.
First, i check if there's a specific day in the input msg and assign the correct string value to my var.
If there's none, i get current date and day of the week as an int value, and using switch statement assign the right string to it aswell.
The thing, that got me thinking, is there're 2 ways i could use the switch stmt.
First is checking the var type, and only then executing
if(typeof weekday == "number"){
Second is just letting it run with no result to come
switch (weekday){
case 1:weekday = "monday";
break;
case 2:weekday = "tuesday";
break;
case 3:weekday = "wednesday";
break;
case 4:weekday = "thursday";
break;
case 5:weekday = "friday";
break;
case 6:weekday = "saturday";
break;
case 0:weekday = "sunday";
break;
}
I know it does like a milisec of difference, and noone would bother, but for the sake of knoledge, optimization and out of pure curiosity, what is faster ?
Considering a case where the weekday would be having a string value.
For if case : It will check if type is "number" and will return false, and will not execute further.
For switch case : It will check against all the 7 cases, if they match, and because it's a string, nothing will be done.
It's not hard to guess which one saves time...

Javascript string coming from object comparison not working in switch

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.

Is It Possible to Generate Case Statements with a Loop?

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.

Is it possible to add cases to switch statement in javascript?

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.

How to Display something depending on variable given in angular

I need to show a word that is attributed to a number, in AngularJS.
Through the controller I send to the view a variable $game.complexity, and complexity can be a number from 1 to 4. I want to take that number and show it as a word:
1 ---> easy
2 --->medium
what I initially thought was that maybe it would work with a cutstom filter:
var filtersModule = angular.module("ttmatchApp.Filters", [])
filtersModule.filter("complexityFilter", function(){
return function(value){
switch(value)
{
case 1:
return "easy"
break;
case 2:
return "medium"
break;
case 3:
return "hard"
break;
case 4:
return "very hard"
break;
}
}
})
and call it like this:
<p>{{game.complexity | complexityFilter:game.complexity}} complexity</p></div>
i also tried it like this:
<p>{{game.complexity | complexityFilter}} complexity</p></div>
I define $scope.game within a controller, and i give it the necessary data through a json file. Other scope elements such as game.name work well, and show.
the filtersModule is also linked to the main module.
Do i have to introduce the filter to the controller as well?
Am i using the wrong method?
Once game.complexity is evaluated in the expression, it is outputted as a string. That means that your switch case should be on strings and not integers - "1" instead of 1, etc..
Edit: I was wrong, the expression is evaluated into a string, but the filter is still within that expression, so it receives game.complexity still as a number. The problem was what you solved in the comments.

Categories