LastIndexOf array returns -1 when start undefined

in javascript, an array instance has two methods:

[].indexOf(searchvalue [,start]) 

and

 [].lastIndexOf(searchvalue [,start]) 

behaves strangely if the "start" parameter is undefined:

 [1,2,3].lastIndexOf(2) // 1 [1,2,3].lastIndexOf(2,undefined) // -1 [1,2,3].indexOf(2,undefined) // 1 

this happens in chrome and firefox, so the theory of indexOf and lastIndexOf differently refers to undefined "

+4
source share
3 answers
 array.lastIndexOf(searchElement[, fromIndex]) 

fromIndex The index from which to start the search in the opposite direction. By default, the length of the array, i.e. the whole array will search. If the index is greater than or equal to the length of the array, the entire array will search. If it is negative, it is taken as the offset from the end of the array. Note that even if the index is negative, the array is still executed on the reverse side. If the calculated index is less than 0, -1, i.e. the array will not search.

[1,2,3].lastIndexOf(2,undefined) same as [1,2,3].lastIndexOf(2, 0) , so only the first element will be checked.

[1,2,3].lastIndexOf(2, 0) will return -1 .

[1,2,3].lastIndexOf(1, 0) will return 0 .

+4
source

array.indexOf() starts testing at the specified point and then continues to move forward until it finds an element in the array that matches the specified value. Therefore, when you use [1,2,3].indexOf(2,undefined) , it starts with an array element with index 0 (which undefined converted to) and continues to check each element:

 2 == 1 // false 2 == 2 // true, returns index 1 

array.lastIndexOf() , however, begins to test back from the specified point. Therefore, when you use [1,2,3].lastIndexOf(2,undefined) , Javascript starts with an array element with index 0, then tries to continue backward:

 2 == 1 // false, no more elements to test, return -1 
+2
source

Here is a standard implementation of lastIndexOf array. Javascript Array lastIndexOf () Method

Note that:

 var from = Number(arguments[1]); if (isNaN(from)) { from = len - 1; } else { from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; else if (from >= len) from = len - 1; } 

It was originally supposed that from is 0, but it’s actually NaN. Possible conclusion: the implementation of mozilla or webkit is not what you want

Another Javascript JavaScript Array Index Method: Method

You can see it directly using

  var from = Number(arguments[1]) || 0; 
-1
source

All Articles