indexOf - 在字符串中搜索值,如果没有则做某事

indexOf - search value in string, if not do something

我有公式:

Total_ID = id1,id2,id3,...,id10

如果myid包含在数组“total_ID”中,做AAA;

我使用:

if (( total_ID.split(",").indexOf(myid.toString()) && (myid !=””))
{AAA}

如何更改我的上述条件公式:

如果 myid 包含在 Total_ID 中,做 AAA

提前致谢

您可以查看是否indexOf() returns -1

根据MDN

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

Total_ID = 'id1,id2,id3,id10';
myid = 'id4';
if (Total_ID.split(",").indexOf(myid) == -1){
  console.log('not found');
}

或者,您可以使用 Array.includes() 来简化它:

Total_ID = 'id1,id2,id3,id10';
myid = 'id4';
if (!Total_ID.split(",").includes(myid)){
  console.log('not found');
}