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")
How about this?
if ( this.id in { "a":1, "b":1, "c":1, "d":1 } ) {
...
}
... or this?
if("abcd".indexOf(this.id) > -1) {
...
}
1 as the dummy value, though.if ( ['a','b','c','d'].indexOf( this.id ) >= 0 ) { ... }
or
if ( this.id in {'a':0,'b':0,'c':0,'d':0} ) { ... }
this.id is 'a', the first example wouldn't know it.in version if you need wide browser support since indexOf doesn't have as much cross-browser support.in version a bit by getting rid of the quotation marks around the property names in the object. As long as the IDs are valid javascript identifiers, you don't need em.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)) {
...
}
if(/^(val1|val2|val3)$/.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]){...}