tags:

views:

101

answers:

3

How can i shorten this code? I want to return all values except "abc" or "xyz" or "pqr"

return this.value != "abc" && this.value != "xyz"  && this.value != "pqr";
+1  A: 

You can use an array:

return ["abc","xyz","pqr"].indexOf(this.value) == -1;

Or an object:

return !({"abc":1,"xyz":1,"pqr":1}).hasOwnProperty(this.value);
Gumbo
surprisingly the first statement gives an error in IE7 but works well in all other browsers
Hitz
It seems that Internet Explorer has that method not yet implemented in version 7.
Gumbo
The object scheme does not work.Consider this.value === 'toString'.You can fix it by using hasOwnProperty instead
Mike Samuel
+1  A: 

2 most common ways are:

  1. regex

    /^(abc|xyz|pqr)$/.test(this.value)

  2. object property lookup

    this.value in ({'abc':1,'xyz':1,'pqr':1})

Note that regex-based solution (#1) will most definitely be slower than plain comparison (your version) or property lookup (#2).

Also, remember that property lookup is not very reliable, as it might report false positives for any key that's named the same as any of Object.prototype.* properties (e.g. "toString", "valueOf", etc.)

kangax
A: 

May I ask why you want it shortened? Like others have pointed out you probably can't gain much performancewise, and what you have is pretty readable.

Teknolog
+1 - I agree. Unless your list of strings to test against is getting into the range of dozens, I'd stick with this method. Readable, understandable, cross-platform...
nickf