有没有一种使用JavaScript或jQuery更简短的方式来编写以下内容?
if (this.id==="a" || this.id==="b" || this.id==="c" || this.id==="d")
if (this.id==="a" || this.id==="b" || this.id==="c" || this.id==="d")
这个怎么样?
if ( this.id in { "a":1, "b":1, "c":1, "d":1 } ) {
...
}
... or this?
if("abcd".indexOf(this.id) > -1) {
...
}
1
作为虚拟值。 - ClosureCowboyif ( ['a','b','c','d'].indexOf( this.id ) >= 0 ) { ... }
或者
if ( this.id in {'a':0,'b':0,'c':0,'d':0} ) { ... }
this.id
是'a'
,第一个例子就不会知道它。 - ClosureCowboyin
版本的长度。只要 ID 是有效的 JavaScript 标识符,你就不需要它们了。 - user113716一种可能性是使用switch语句。
switch(this.id){case"a":case"b":case"c":case"d":
//do something
}
if (/^[abcdef]$/.test(this.id)) {
...
}
if(/^(val1|val2|val3)$/.test(this.id)) { ... }
- Jason LeBrun