By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,417 Members | 1,856 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,417 IT Pros & Developers. It's quick & easy.

Switch..Case Statement Question.

P: n/a
Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}
Thank you.
Andy.

Jul 23 '05 #1
Share this Question
Share on Google+
21 Replies


P: n/a
Andy wrote on 28 feb 2005 in comp.lang.javascript:
Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:
did you test it yourself? If not why not?
switch(state){
case 1-35:
case 37:
do something_1;
break;


this part will execute if "state" is -34 or 37,
because 1-35 is 34, I think.

But please test it yourself.
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #2

P: n/a
Lee
Andy said:

Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}


With less effort and much less wait time, you could have just tested
your sample code yourself. Your first case will match any state that
equals your index value of -34 (1-35).

Jul 23 '05 #3

P: n/a
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.

Jul 23 '05 #4

P: n/a
Andy wrote:
Can someone tell me if the following Switch...Case construct is valid?
No.
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.


You cannot. The expression after the case keyword is compared for
strict equality (===) with the expression in the switch statement. In
other words,

switch(2) {
case '2': /* This statement list will not be evaluated. */
}

the statement list for case '2' will not be evaluated because the
expressions do not evaluate to the same type (one is a number, the
other is a string).

You have little choice but to use an if statement.

if(((1 <= state) && (35 >= state)) || (37 == state)) {
/* Between 1 and 35 (inclusive) or is 37 */
something_1();
} else if(36 == state) {
/* Is 36 */
something_2();
} else if((38 <= state) && (50 >= state)) {
/* Between 38 and 50 (inclusive) */
something_3();
}

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5

P: n/a
Andy wrote on 28 feb 2005 in comp.lang.javascript:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Please do not use usenet as a form of email. you are replying to many
here, so quote relevant part of the mail you answer on. Remember
netiquette.

Now "I" have to quote from your old posting:switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;

You could do:

state = 20;
switch(true){
case state>=1&&state<=35:
case state==37:
do something_1;
break;
case state==36:
do something_2;
break;
case state>=38&&state<=50:
do something_3;
break;
case default:
alert('default')
}

This however in my view defies usefulness of switch().
anyway if-else is much more robust:

state = 20;
if ((state>=1&&state<=35)||state==37){
do something_1
else if (state==36)
do something_2
else if (state>=38&&state<=50)
do something_3
else
alert('default');

[not tested]

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #6

P: n/a
Andy wrote:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.

This is where the "greater than or equal to" and "less than or equal to"
operators come in handy. For instance, ">=1 && <=35" is between one and
thirty-five.
Jul 23 '05 #7

P: n/a
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

Jul 23 '05 #8

P: n/a
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #9

P: n/a
rh
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?


I'd have to say "No", because the former is syntactically (block)
deficient. ;-)

However, the "switch/case" idiom can be more useful, or at least more
appropriate to use, in some circumstances because of the nature of the
structural encapsulation it provides for a specific filtering task.

The choice shouldn't have any effect on the result of the execution,
but it can have a marked effect on the readability and maintainability
of the code.

../rh

Jul 23 '05 #10

P: n/a
Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.

Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?

You remind me of the playground rules in tag. No electricity except in
freeze tag. No tagbacks.

You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.

Jul 23 '05 #11

P: n/a
bumbleguppy wrote:
Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.
A Google webpage that is not a Usenet application but an attempt at a
web-based application for interfacing to Usenet.
Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?


Are you actually stupid enough to believe that rubbish that you spout?

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #12

P: n/a
bumbleguppy wrote:
Welcome to 2005 guy.

I don't know what archaic usenet application you are
using to view this thread, but I however am
Whatever _you_ may be doing is irrelevant. Usenet is a one-to-many
communication medium where the needs/wishes/interest of the many
outweigh all personal preferences. Saving yourself a little effort in
exchange for wasting the time of hundreds or thousands of others is
objectionable and likely to be considered rude.
writing this reply in a text box in a
webpage. A Google webpage.
Recent changes in google's Usenet interface have rendered it on a par
with the very worst providers of web-based access to Usenet
(Forum4designers.com) and the only reasonable advice now possible is to
abandon using google groups in favour of some superior web-based
provider or (preferably) access Usenet directly through an NTTP server
(as provided by any ISP worthy of the name) using real newsreader
software.
Why would I want to load an html page
comp.lang.javascirpt is a plain text _only_ newsgroup.
with the same quoted statemaents
ad naseum when,
The convention is to _only_ quote the material that is being respond to,
and trim the rest. It is done to provide a context for the response.
in my web browser, I can scoll up to see
the relevent subject material?
What ever you can do says nothing bout what the many who read your posts
can do (or what they would prefer to do). You (alone) will never be the
arbiter of what it correct.
You remind me of the playground rules in tag. No
electricity except in freeze tag. No tagbacks.
Games, and many other things, work best when everyone plays by the same
rules. The 'rules', the conventions for Usenet posting, have been around
for a long time (more than 20 years), evolved to suite the medium, and
can be found by reading the groups FAQ (the reading of which is a
pre-requisite for participation in any technical Usenet group that
provides a FAQ).
You saw my post. You understood the meaning. Save
your sophomoric nerdish and arbitrary instructions to
the next newbie that wants to "fit in" with the geeks.


Are you inviting that active hostility of regulars on this group?

Richard.
Jul 23 '05 #13

P: n/a
rh wrote:
Evertjan. wrote:
bumbleguppy wrote: <snip>
switch(true){
case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;
<snip> is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?


I'd have to say "No", because the former is syntactically
(block) deficient. ;-)

<snip>

To be honest I find the former superior, but only because of one
omission in the latter; there should be an - else - in front of the
second - if - statement. The conditions are mutually exclusive and there
is no reason to evaluate the second after the first has evaluated to -
true.

Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility
may be in other contexts).

Richard.
Jul 23 '05 #14

P: n/a
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.

---
John W. Kennedy
"Those in the seat of power oft forget their failings and seek only the
obeisance of others! Thus is bad government born! Hold in your heart
that you and the people are one, human beings all, and good government
shall arise of its own accord! Such is the path of virtue!"
-- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis)
Jul 23 '05 #15

P: n/a
John W. Kennedy wrote on 06 mrt 2005 in comp.lang.javascript:
Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.


That being my [inconsequental in this example] mistake
does not per se make it less useful then the switch(true)
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #16

P: n/a
Lee
bumbleguppy said:

Welcome to 2005 guy.
You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.


Don't be so quick to rule out the possibility that you lack the
experience to understand why the request is reasonable. That's
a really good way to make yourself appear to be spectacularly
ignorant.

Insulting people for making a request whose value you fail to
understand makes you look that much worse.

Jul 23 '05 #17

P: n/a
rh
Richard Cornford wrote:

<..>
Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility may be in other contexts).


So it would seem, although I think that's in large part due to lack of
some Javascript switch/case facility that's seen in other languages.

In the greater scheme of things, I tend to view the distinction between
switch/case and if/else as the former being more for conditioning
(i.e., setup) and the latter more for program flow control. Of course,
if/else is always favoured and appropriate when the set of cases to be
distinguished is small.

Not a perfect substitute, but perhaps helpful in the context of numeric
range filtering, would be something like:

<script type="text/javascript">

Number.prototype.inRng = function( str ) {
var testSet = str.split( "," );
for ( var k = 0; k < testSet.length; k++ ) {
var rng = testSet[ k ]
.replace( /(\d|y)\s*-\s*([+-]?(\d|I))/g, "$1#$2" )
.split( "#" );
if ( typeof rng[ 1 ] == "undefined" ) rng[ 1 ] = rng[ 0 ];
if ( this >= rng[ 0 ] && this <= rng[ 1 ] ) return true;
}
return false;
}

var z = 33;

switch ( true ) {

case z.inRng( '1-35, 37' ) :
//..
break;

case z == 36 :
//..
break;

case z.inRng( '38-50' ) :
//..
break;

default :
//..
}
</script>

../rh

Jul 23 '05 #18

P: n/a
rh wrote on 06 mrt 2005 in comp.lang.javascript:
Number.prototype.inRng = function( str ) {


Try this:

<script type="text/javascript">
var myCase = 'myCase';
var mydo = 'mydo';
var myDefault = 'myDefault';
var res,a;

function mySwitch(){
var base = mySwitch.arguments[0]
for (var i=1;i<mySwitch.arguments.length;i++){
a = mySwitch.arguments[i]
if(i==0)var val=a
else if (a==myCase)res=false
else if ((a==mydo&&res)||a==myDefault){
eval(mySwitch.arguments[++i])
return }
else if (!res){
if (/\d+\-\d+/.test(a))
res = (base>=1*a.replace(/-\d+/,''))&&
(base<=1*a.replace(/\d+-/,''))
else
res = (base==a)
}
}
}
mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)

</script>

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #19

P: n/a
rh
Evertjan. wrote:
rh wrote on 06 mrt 2005 in comp.lang.javascript:
Number.prototype.inRng = function( str ) {
Try this:


<..>

mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)


Well, you'll have to be given points for a adopting an inventive and
novel approach, but I don't think I want to go there.

Note that as soon as you call the "mySwitch" function, you've lost the
current execution context. That means that if you want to do something
that's actually useful in a "mydo", such as test or assign to a local
variable from the original context, you're snookered.

../rh

Jul 23 '05 #20

P: n/a
Evertjan. wrote:
John W. Kennedy wrote on 06 mrt 2005 in comp.lang.javascript:

Evertjan. wrote:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;


Actually, yes. You're missing an 'else'.

That being my [inconsequental in this example] mistake
does not per se make it less useful then the switch(true)


I once saw, in the real world, in a production program, 100 (yes,
literally 100) mutually exclusive cases IF'ed without a single ELSE.

---
John W. Kennedy
"Those in the seat of power oft forget their failings and seek only the
obeisance of others! Thus is bad government born! Hold in your heart
that you and the people are one, human beings all, and good government
shall arise of its own accord! Such is the path of virtue!"
-- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis)
Jul 23 '05 #21

P: n/a
JRS: In article <d0*********@drn.newsguy.com>, dated Sun, 6 Mar 2005
09:33:37, seen in news:comp.lang.javascript, Lee
<RE**************@cox.net> posted :
bumbleguppy said:

Welcome to 2005 guy.

You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.


Don't be so quick to rule out the possibility that you lack the
experience to understand why the request is reasonable. That's
a really good way to make yourself appear to be spectacularly
ignorant.

Insulting people for making a request whose value you fail to
understand makes you look that much worse.


With the consequence, which probably does need to be spelt out, that the
regular experts will ignore the questions of such posters, confining
themselves to correcting the errors that they make in their responses,
if any, to others.

Whatever suits the convenience of the expert regulars increases the
chances of getting good answers.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 23 '05 #22

This discussion thread is closed

Replies have been disabled for this discussion.