Navin Rauniyar
Navin Rauniyar

Reputation: 10525

How can I shorten the or operator?

if(x=='a'||x=='b'||x=='c'||x=='d'||x=='e'||x=='x'||x=='y'||x=='z'){
...
}

If I do like this, won't work anymore:

if(x=='a'||'b'||'c'||'d'||'e'||'x'||'y'||'z'){
...
}

So, what's the prefered way to do this?

Upvotes: 0

Views: 80

Answers (1)

zerkms
zerkms

Reputation: 254926

I cannot resist to put an answer after my comment gained 10 12 13 upvotes :-)

Use either:

  1. ['a', 'b', 'c', 'd', 'e', 'x', 'y', 'z'].indexOf(x) >= 0

  2. x.match(/^[abcdexyz]$/)

  3. 'abcdexyz'.indexOf(x) > -1 credits to @bigp

Just for fun: http://jsperf.com/single-char-lookup-zerkms

Upvotes: 5

Related Questions