How can I implement this behavior in JavaScript Switch Statements
expression = 'all' or '1' or '2'
switch (expression)
{
case "all" : print case 1 and case 2
case "1" : print only case 1
case "2" print only case 2
}
How can I do that? If there’s no way to do something like that in JavaScript, I want to know an alternative solution.
5
Answers
You should read this first: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
This is essentially how you would handle that in Javascript.
Now, if you want types that is another conversation.
Maybe a ‘mapping’ object would fit your needs.
Check the key on the object, call that case if needed.
On
all
, loop overObject.values(obj)
to call all the casesYou can use the switch statements like this:
Please note that a block will execute until a break statement is encountered. If you do not use the break statement, the execution will fall through. For example, this statement will print 1, 2, and then 1 again because we are not using the break statement in the first case:
expression = ‘all’ // "1" or "2"
You can construct your own "switch" kind of
Or you can use a reverse switch trickery
You could take two condition instead.