IndexOf method in Javascript

I am trying to understand a lot of basic Javascript components and one of the things I came across is a line of code saying

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

      

varX is an array of strings and varY, which is obviously one of the strings in this array. Remove the "0" and my understanding is that the code is just looking for varY with an array varX. But I don't know what 0 does and what it means for the if statement. I did my best to watch this and didn't really understand anything.

+3


source to share


3 answers


According to MDN docs :

fromindex

      

Index to start searching. If the index is greater than or equal to the length of the array, -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 viewed from front to back. If the computed index is less than 0, then all arrays will be searched. Default: 0 (searches the entire array).



So, going to "0" is pretty much pointless as it starts searching at 0 anyway.

+3


source


From mdn :



arr.indexOf(searchElement[, fromIndex = 0])

fromIndex

      

Index to start searching. If the index is greater than or equal to the length of the array, -1 is returned, which means the array will not be searched. If the supplied 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 viewed from front to back. If the computed index is less than 0, then the entire array will be searched. Default: 0 (searches the entire array).

+2


source


0

is the index from which you start your search. By default this is 0

, so you don't need to pass this parameter.

0


source







All Articles