JRS: In article <bu************ @ID-161723.news.uni-berlin.de>, seen in
news:comp.lang. javascript, lallous <la*****@lgwm.o rg> posted at Fri, 16
Jan 2004 17:05:59 :-
"Robert Scheer" <rb******@my-deja.com> wrote in message
news:cf******* *************** ****@posting.go ogle.com...
I am trying to use switch this way, without success:
//thedata is a numeric variable
switch (thedata) {
case < 10:
...
case < 20:
...
case <= 30:
...
}
It seems that switch can only test for single string values. Can't I
make this kind of test using switch?
You can : see below previous response.
Responses should go after trimmed quotes, as per Wednesday FAQ.
You can't use 'switch' like that...you can check for exact values only, as:
Well, yes and no.
If you need to compare for ranges rather than exact values then the 'if/else
if' is what you need:
if (x < 10) { ...... }
else if (x > 30) { .....}
else { .......}
No. It can be used, but it is not needed.
var X = 265 // the variable
switch(true) {
case X<10 : alert('<10') ; break
case X<20 : alert('<20') ; break
case X<30 : alert('<30') ; break
default : alert('big') }
A post here or elsewhere a few days/weeks ago provided a clue from which
the above is derived. The code appears to be about as long as that with
nested IF; appears legal; can easily be laid out readably; works (at
least in eval in MSIE4); and ISTM that it should be of similar speed.
Advantage: case & break fulfil the role of brackets; more typing, but
easier to pair them up correctly.
To confuse readers : change true to false and reverse the relational
operators ( < to >= ).
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.