/    Sign up×
Community /Pin to ProfileBookmark

Checking equivalency between one value and a range

I want to check whether a variable is equivalent to one of several. Basically i want to do this…

[code]if ( myColor != (‘red’ || ‘green’ || ‘blue’) ) {
alert(‘myColor is not a primary color!’);
}[/code]

is something like this possible? i know i could use a switch statement or if statements, but that seems more verbose than necessary…

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@bcamp1973authorJan 21.2010 — i also realize i could do this, but it seems odd to repeat it...

if ( myColor != 'red' && myColor != 'green' && myColor != 'blue') ) {
alert('myColor is not a primary color!');
}
Copy linkTweet thisAlerts:
@mrhooJan 21.2010 — A switch statement is the most efficient, but you can use a regular expression if you want to type less, and are not concerned with efficiency.

if(!/^(red|green|blue)$/.test(myColor))alert('myColor is not a primary');
Copy linkTweet thisAlerts:
@bcamp1973authorJan 21.2010 — thank you!
Copy linkTweet thisAlerts:
@rnd_meJan 21.2010 — an object is even better than a switch, and much faster than a regexp, plus you can later modify the object at runtime (adding/deleting oks), unlike a switch.

[CODE]
var okColors={red:1, green:1, blue:1};
if ( ! okColors[myColor] ) {
alert('myColor is not a primary color!');
}[/CODE]
×

Success!

Help @bcamp1973 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...