var num = [26, 16, 41, 32, 16, 28, 16, 41];
console.log(num.indexOf(41));// 2
console.log(num.indexOf(41, 2)); // 2
console.log(num.indexOf(16, -1)); // -1 why?
console.log(num.indexOf(16, -2)); // 6
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (2)
Second argument to
indexOf
is the starting offset. Negative offsets start from the end of the array. Also if an element is not found -1 is returned. So if you start at the last element (-1th?) There is only 41 so 16 is not an element hence returning -1. If you start from the second to last element your search array is [16, 41] which does have 16 so it outputs the position in the overall array of that element (i.e. 6th position).Always remember that the search is always in a forward direction.
The negative index tells where the starting position to search; it does not mean search backwards.
You asked it to start searching from position -1 which is from the number 41 going forward. So there is nothing.