Javascript:将变量与值数组进行比较

Dav*_*cia 8 javascript arrays

在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)


hsz*_*hsz 9

试试:

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}
Run Code Online (Sandbox Code Playgroud)

  • 有关兼容性,请参阅http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-internet-explorer-browsers (3认同)