...

View Full Version : Check for equivalance to multiple values?



JoshuaL
09-09-2011, 06:54 PM
Hi all,
I have to check for several possible values of a variable and I currently do it like so:

(SHIP_TYPE == "M" || SHIP_TYPE == "S" || SHIP_TYPE == "X")

But this seems overly manual to me. I'm imagining something like the SQL "IN" function:

SHIP_TYPE IN ('M','S','X')

Does such a thing exist in JavaScript, or do I need to write my own function?

mrhoo
09-09-2011, 08:08 PM
You can use a regular expression-


if(/^[MSX]$/.test(SHIP_TYPE)){

There is an 'in' operator, but you have to create an object and instantiate all the properties:



var SHIP_TYPE='S';
if(SHIP_TYPE in {M:1,S:1,X:1}){

jmrker
09-09-2011, 08:12 PM
How about:


if ('MSX'.indexOf(SHIP_TYPE) != -1) { alert('Found match') } else { alert('NO match found'); }

The position of the match could also be used in a switch statement


var posn = 'MSX'.indexOf(SHIP_TYPE);
switch (posn) {
case 0: do_something( 'M'); break;
case 1: do_something( 'S'); break;
case 2: do_something( 'X'); break;
default : alert('No match found'); break;
}

Old Pedant
09-09-2011, 08:31 PM
I like if ('MSX'.indexOf(SHIP_TYPE) != -1) ... as being the simplest, but if we are tossing around ideas...



function doMthing( ) { ... }
function doSthing( ) { ... }
function doXthing( ) { ... }

var actions = { "M" : doMthing, "S" : doSthing, "X" : doXthing };
if ( SHIP_TYPE in actions ) actions[SHIP_TYPE]( );

jmrker
09-09-2011, 09:51 PM
I like if ('MSX'.indexOf(SHIP_TYPE) != -1) ... as being the simplest, but if we are tossing around ideas...



function doMthing( ) { ... }
function doSthing( ) { ... }
function doXthing( ) { ... }

var actions = { "M" : doMthing, "S" : doSthing, "X" : doXthing };
if ( SHIP_TYPE in actions ) actions[SHIP_TYPE]( );


Well, that's pretty neat too!
:thumbsup:

Old Pedant
09-09-2011, 10:08 PM
More than one way to deprive a feline of its outer integument.

Especially in programming.

Most especially in JavaScript.

jmrker
09-09-2011, 10:11 PM
More than one way to deprive a feline of its outer integument.

Especially in programming.

Most especially in JavaScript.

I guess we can not just "skin a cat" anymore with PETA present! :D

rnd me
09-09-2011, 10:21 PM
direct access is simpler than using IN:

if({M:1,S:1,X:1}[SHIP_TYPE]){ ... }

Old Pedant
09-09-2011, 10:24 PM
LOL! Man, that feline keeps getting bigger and bigger. Are we up to the size of a tiger, yet?

JoshuaL
09-09-2011, 11:10 PM
Wow, thank you all! I had no idea there was an "in" operator. And the direct access concept is new to me as well. So many good options. I'll play around with all of these. Much fun! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum