Javascript中的indexOf方法

3

我正在尝试理解JavaScript的许多基本组件之一,其中我遇到的一行代码是:

if (varX.indexOf(String(varY),0) < 0)    

varX是一个字符串数组,而varY显然是该数组中的一个字符串。去掉",0",我理解这段代码只是在查找数组varX中的varY。但是我不知道",0"的作用以及对if语句的意义。我尽力查找了一些资料,但并没有找到什么有用的信息。


2
",0" 表示搜索的起始位置。它默认从0开始,因此这是多余的。 - Compass
1
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf - 你在哪里查找它的信息? - Bergi
我之前在谷歌上搜索了一些东西,但我想我的搜索方式可能不是最好的。现在回想起来,我有点后悔没有在搜索中找到它。非常感谢你的帮助! - JoeL
3个回答

3
根据 MDN文档
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开始进行搜索。

需要注意的是,提供的代码示例中采用这种方式没有充分的理由,因为0是默认值。 - Paul
非常感谢!我想点赞,但显然我需要15个声望才能这样做,而我还没有那么多。不过我已经给了一个检查! :) - JoeL

2

来源于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 是你开始搜索的索引位置。默认情况下它是 0,所以你不需要传递这个参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接