在javascript我正在做以下工作正常.
if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能缩短它?类似以下内容.
if (myVar IN ('25','26','27','28')) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
要么
if(myVar.indexOf("25","26","27","28") > -1) ) {//do something}
Run Code Online (Sandbox Code Playgroud)
Sat*_*pal 18
您可以使用Array.indexOf()它返回第一个索引,在该索引处可以在数组中找到给定元素,或者-1它是否不存在.
使用
var arr = [25, 26, 27, 28];
console.log(arr.indexOf(25) > -1);
console.log(arr.indexOf(31) > -1);Run Code Online (Sandbox Code Playgroud)
Array.includes()方法也可以用它返回boolean.
var arr = [25, 26, 27, 28];
console.log(arr.includes(25));
console.log(arr.includes(31));Run Code Online (Sandbox Code Playgroud)
试试:
if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28410 次 |
| 最近记录: |