[removed] compare variable against array of values

前端 未结 5 878
滥情空心
滥情空心 2021-02-06 07:12

In javascript I am doing the following which works fine.

if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
 {
   //do something
 }

5条回答
  •  春和景丽
    2021-02-06 07:24

    You can use Array.indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

    Use

    var arr = [25, 26, 27, 28];
    console.log(arr.indexOf(25) > -1);
    console.log(arr.indexOf(31) > -1);


    Array.includes() method can also be used it returns boolean.

    var arr = [25, 26, 27, 28];
    console.log(arr.includes(25));
    console.log(arr.includes(31));

提交回复
热议问题