开发者

Shorter code for this JavaScript "if" statement

Is there a 开发者_StackOverflow中文版short way to write the following using either JavaScript or jQuery?

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


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, compared 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜