This question already has answers here:
Switch Statement, it does not work with prompt
(3 answers)
Closed 1 year ago.
What is wrong with this code? The switch statement is not taking the input. If I declare the value of variable 'a' directly then it is showing the output.
var a = prompt("value");
console.log(fun(a));
function fun(value)
{
let ans = "";
switch(value)
{
case 1:
ans = "alpha";
break;
case 2:
ans = "beta";
break;
case 3:
ans = "gamma";
break;
}
return ans;
}
You are comparing integers with string, just add quotes to cases
var a = prompt("value");
console.log(fun(a));
function fun(value)
{
let ans = "";
switch(value)
{
case "1":
ans = "alpha";
break;
case "2":
ans = "beta";
break;
case "3":
ans = "gamma";
break;
}
return ans;
}
Switch uses strict equality (===) to match Switch expression to case clauses.
In your code, value is a string but your case clauses are numbers, so because of strict equality, string value won't be coerced to match the case clauses which are numbers.
You can convert the result of prompt to a number before passing it to the function.
Change
var a = prompt("value");
to
var a = Number(prompt("value"));
Related
function getFieldType(value){
var type = "";
switch(value){
case "TEXT_BOX":
type=FieldTypeEnum.TEXT_BOX;
break;
case "PASSWORD":
type=FieldTypeEnum.PASSWORD;
break;
case "CHECK_BOX":
type=FieldTypeEnum.CHECK_BOX;
break;
case "RADIO_BUTTON":
type=FieldTypeEnum.RADIO_BUTTON;
break;
case "DROP_DOWN":
type=FieldTypeEnum.DROP_DOWN;
break;
case "SEARCH_CARD_BOX":
type=FieldTypeEnum.SEARCH_CARD_BOX;
break;
case "STATE_DROP_DOWN":
type=FieldTypeEnum.STATE_DROP_DOWN;
break;
case "ID_DROP_DOWN":
type=FieldTypeEnum.ID_DROP_DOWN;
break;
case "GENDER_DROP_DOWN":
type = FieldTypeEnum.GENDER_DROP_DOWN;
break;
default:
type = "";
}
return type;
}
I want to combined three drop down box (STATE_DROP_DOWN, ID_DROP_DOWN, GENDER_DROP_DOWN)into one .
Means I want something like below :
case String.endwith("_DROP_DOWN"):
type=FieldTypeEnum.ID_DROP_DOWN;
break;
Is it possible in JavaScript? If yes then how?
It is possible, in a javascript switch/case statement you can compare for string equality (which evaluates to true or false) or more complex statements which just as when testing for string equality, also evaluate to true or false (e.g. String.endwith("_DROP_DOWN")). However personally I would prefer the following:
STATE_DROP_DOWN:
// intentional fall through
ID_DROP_DOWN:
// intentional fall through
GENDER_DROP_DOWN:
//.. do your stuff
break;
I believe this way it is more clearly through which switch case you are falling in a certain situation.
You can put a ternary operator in the case, and test if it ends with "DROP_DOWN" return value otherwise blank string.
switch(value){
case value.endsWith("_DROP_DOWN") ? value : '' {
type=FieldTypeEnum.ID_DROP_DOWN;
break;
}
}
This question already has answers here:
JavaScript conditional switch statement
(5 answers)
Closed 7 years ago.
I just started learning about the switch command in JavaScript, and was wondering if the cases could be constructed so as to include inequalities (<, >, <= and >=), instead of equality (==). Also, can one control whether it is a strict equality (===) or not? The following code does not even bring up a prompt, so I'm not sure if I've coded correctly:
var a = prompt("Please input a number.");
switch (a) {
case { < 1 }:
alert("less than 1");
break;
case { < 2 }:
alert("less than 2");
break;
case { < 3 }:
alert("less than 3");
break;
default:
alert("greater than or equal to 3");
}
It is actually possible, if you do it like this. The case whose expression evaluates to true is executed.
var a = +prompt("Please input a number.");
switch (true) {
case (a<1): alert("less than 1");
break;
case (a<2): alert("less than 2");
break;
case (a<3): alert("less than 3");
break;
default: alert("greater than or equal to 3");
}
Note: Personally I feel you should use if-else for this purpose.
Is there a way to create multiple cases in a single Javascript switch statement?
In my code I receive the value of a field via jQuery.
Is it possible that one case checks for string regex and another for number of the same variable?
I am thinking along the lines of:
var field = $(this).val();
var msg;
switch (field)
{
case field.test('Yes'):
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
Although I saw here: Switch statement for string matching in JavaScript
That the way to use switch on strings is by sending the switch statement a "true" value.
What would be the most concise (and correct!) way to achieve this?
OK, compiling both answers above my code that worked and was most elegant IMO is:
var fieldVal = $(this).val();
var msg;
switch (true)
{
case /Yes/.test(fieldVal):
msg = "FOO";
break;
case fieldVal > 10 :
msg = "BAR";
break;
}
this works as separate if statements since we are evaluating whether or not the case returns true but in a clearer and more concise way that could give us the option to add totally disparate test statements in one switch.
the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main -
switch(true)
You can't the case need to single value, that's compared to switch expression, but you can put multiple cases to execute the same code:
switch (field) {
case 'Yes':
case 'yes':
case 'YES':
msg = "FOO\n";
break;
case 10:
msg = "BAR\n";
break;
}
but in order to use test as case you can pass true to switch (I found that trick in some open source project):
switch (true) {
case field.test('Yes'):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
but this is the same as if/else
Note: you're using test() incorrectly, it's a method of a regex object, so you need /Yes/.test(field) rather than field.test('Yes'). Anyway...
If you've only got two cases as shown then I'd use an if/else/else if structure:
var field = $(this).val();
var msg;
if(/Yes/.test(field)) {
msg = "FOO\n";
} else if (field === 10) {
msg = "BAR\n";
}
If you need to add additional cases I'd just add extra if else {} branches on the end.
If you have several specific numeric cases you might consider putting them in a switch with the regex tests in a default at the end:
switch (field) {
case 10:
msg = "BAR\n";
break;
case 30:
msg = "whatever\n";
break;
case 50:
msg = "hi\n";
break;
default:
if (/Yes/.test(field)) {
msg = "FOO\n";
else if (/No|N|False|/i.test(field)) {
msg = "blah\n";
}
break;
}
The switch (true) option you alluded to in the question is really just a messier version of an if/else/else if, so it doesn't really make sense unless you have some fall-through cases:
switch(true)
case /Yes/.test(field):
case /Y/.text(field):
case /Whatever/.text(field):
msg = "FOO\n";
break;
case field == 10:
msg = "BAR\n";
break;
}
...and even then an if with multiple conditions joined by || arguably just as tidy with appropriate newlines, and combining multiple regexes into a single one is probably a lot neater.
What regular expression I need to use to correct
if (text.indexOf("+") != -1) {
action = "+";
} else if (text.indexOf("-") != -1) {
action = "-";
} else if (text.indexOf("*") != -1) {
action = "*";
} else if (text.indexOf("/") != -1) {
action = "/";
}
this code
?
EDIT:
and how can I improve this code:
switch (action) {
case "+":
result = parseInt(array[0]) + parseInt(array[1]);
break;
case "-":
result = parseInt(array[0]) - parseInt(array[1]);
break;
case "*":
result = parseInt(array[0]) * parseInt(array[1]);
break;
case "/":
result = parseInt(array[0]) / parseInt(array[1]);
break;
default:
break;
}
Sorry for dull questions I am new in js.
You can use either of these:
var action = text.replace(/.*([+*/-]).*/,'$1');
var match = /[*+/-]/.exec(text);
var action = match && match[0];
If there's the possibility of newlines in your text then change the first to:
var action = text.replace(/[\d\D]*([+*/-])[\d\D]*/,'$1');
Edit: You can improve your switch statement by using, e.g.
// allow floating point values, and also
// don't accidentally interpret "011" as octal
array[0]*1 + array[1]*1;
For more details on why parseInt is probably bad, see this answer.
You can also remove the superfluous default section of your case statement. However, I suspect that your desired "improvement" was making fewer lines. Given that =-*/ are operators in JavaScript (and not methods), I cannot think of any way to avoid having four calculations (i.e. a switch or if/else if).
Whereas in Ruby you could, for example, use array[0].send(action,array[1]) to cover all four cases ;)
I'm having a problem using a mathematical operator in a switch expression.
This is what my code currently looks like:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case "200":
document.write("200!");
break;
case "500":
document.write("500!");
break;
case "100":
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
Explained: the variable "result" has a value of 100. I am trying to use that value with the switch operator, but it just isn't working.
I've also tried using the equation itself as the switch expression, but that doesn't work either.
P.S: I just started out with JavaScript. Bet I missed something obvious...
Change "100" to 100 and it works. switch must be using the semantics of === which means 'type and value are equal' vs ==, which will try to make the types similar and then compare.
EDIT -- here is a screenshot showing it working
You're comparing the number 100 to the string "100", that isn't the same. Try this:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case 200:
document.write("200!");
break;
case 500:
document.write("500!");
break;
case 100:
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
You are using strings in your case statements. Take the quotes (") out and you should be fine.