NotToBrag
NotToBrag

Reputation: 665

Shorten Conditional Statement?

Fairly simple question, not sure what I'm missing here... I have something like this:

if(this == 18 || this == 19 || this == 20 || this == 21) { 
    ...
}

How can I shorten it? I've tried if(this == 18 || 19 || 20...) but that didn't work. I have about 50 more of those values to go so it would be great if I could.

Thanls.

Upvotes: 0

Views: 60

Answers (6)

klamoree
klamoree

Reputation: 115

jQuery also has a similar function inArray()

if( jQuery.inArray( this, [18,19,20,21] ) > -1) { ... }

Upvotes: 0

aljgom
aljgom

Reputation: 9189

how about creating an array and using indexOf?

something like

testArray = [18,19,20,21];
if( testArray.indexOf(this) != -1){
    ...
}

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

Assuming a suitable shim for older browsers:

if( [18,19,20,21].indexOf(this) > -1) {

Or, alternatively:

if( "|"+[18,19,20,21].join("|")+"|".indexOf("|"+this+"|") > -1) {

Upvotes: 4

Joseph
Joseph

Reputation: 119887

If they are sequential, you can do:

if(this >= 18 && this <= 21){
  ...
}

If they are not sequential, you can use an array and indexOf

var values = [18,19,20,21];
if(values.indexOf(this) !== -1){
  ...
}

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191058

Try using an array

if ([18, 19, 20, 21].indexOf(this) >= 0) {
     // ...
}

Upvotes: 0

Ford Filer
Ford Filer

Reputation: 325

EDIT: See answers which use indexOf - much cleaner IMO

Assuming the data isn't sequential numbers (if it is just use this > min && this < max)

You could put them all into an array, then do a foreach on the array. Inside the loop, do a comparison, if it matches do your logic and then break.

Upvotes: 0

Related Questions