开发者

Combining multiple conditions into one in Javascript

开发者 https://www.devze.com 2022-12-08 16:01 出处:网络
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 != \"

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";


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);


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消