我正在尝试理解JavaScript的许多基本组件之一,其中我遇到的一行代码是:
if (varX.indexOf(String(varY),0) < 0)
varX是一个字符串数组,而varY显然是该数组中的一个字符串。去掉",0",我理解这段代码只是在查找数组varX中的varY。但是我不知道",0"的作用以及对if语句的意义。我尽力查找了一些资料,但并没有找到什么有用的信息。
我正在尝试理解JavaScript的许多基本组件之一,其中我遇到的一行代码是:
if (varX.indexOf(String(varY),0) < 0)
varX是一个字符串数组,而varY显然是该数组中的一个字符串。去掉",0",我理解这段代码只是在查找数组varX中的varY。但是我不知道",0"的作用以及对if语句的意义。我尽力查找了一些资料,但并没有找到什么有用的信息。
因此,传入“0”基本上是没有意义的,因为它会从0开始进行搜索。fromindex
The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (Entire array is searched).
来源于MDN:
arr.indexOf(searchElement[, fromIndex = 0]) fromIndex
The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (Entire array is searched).
0
是你开始搜索的索引位置。默认情况下它是 0
,所以你不需要传递这个参数。