最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Shorter code for this JavaScript "if" statement - Stack Overflow

programmeradmin3浏览0评论

Is there a short way to write the following using either JavaScript or jQuery?

if (this.id==="a" || this.id==="b" || this.id==="c" || this.id==="d")

Is there a short way to write the following using either JavaScript or jQuery?

if (this.id==="a" || this.id==="b" || this.id==="c" || this.id==="d")
Share Improve this question edited Oct 8, 2011 at 18:04 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jan 31, 2011 at 2:06 HusseinHussein 42.8k25 gold badges115 silver badges143 bronze badges 2
  • 5 Here's a page to pare the performance of various suggestions below: jsperf./set-memberbship – Jason LeBrun Commented Jan 31, 2011 at 2:21
  • @Jason LeBrun I have a +1 for the nice demo -- but as [more-often-then-not] always, clarity first. I blame my CPU for the slow FF posting ;-) – user166390 Commented Jan 31, 2011 at 3:12
Add a ment  | 

5 Answers 5

Reset to default 6

How about this?

if ( this.id in { "a":1, "b":1, "c":1, "d":1 } ) {
  ...
}

... or this?

if("abcd".indexOf(this.id) > -1) {
   ...
}

if ( ['a','b','c','d'].indexOf( this.id ) >= 0 ) { ... }

or

if ( this.id in {'a':0,'b':0,'c':0,'d':0} ) { ... }

One possibility is a switch statement.

switch(this.id){case"a":case"b":case"c":case"d":
    //do something
}

You can try the following code. Especially when you have more than four test values.

if (/^[abcdef]$/.test(this.id)) {
    ...
}

The inline anonymous hash (d in o) performance was misrepresented in the tests as originally written, because the hash wasn't inline in the test.

Oddly enough, the true inline hash case, pared to the predefined hash case, is much slower in Firefox 4, but 50% faster in Chrome 12.

But a more important point is that d in o misses the point of a hash—that you don't have to iterate to find things.

Two lines, but still pretty short, and by far the fastest:

var o = {a:1,b:1,c:1,d:1};
if(o[this.id]){...}
发布评论

评论列表(0)

  1. 暂无评论