I read Professional JavaScript for Web Developers (third edition) by Nikolai Zakas in an attempt to teach myself JS. However, I am having difficulty using the โLocation Methodsโ section of Chapter 5 on page 118 (in case you have a book). He explains that "the indexOf () method starts searching on the front of the array (element 0) and continues to the end, while lastIndexOf () starts with the last element in the array and continues to move forward." He also explains that "each of these methods takes two arguments: an element to search for and an optional index from which to start looking." He then tries to illustrate this with examples.
As you can see below, to the right of the warning statements, he listed what the correct output will be for each statement specified by the argument (s) provided. I do not understand how these results are determined. For example, how alert (numbers.indexOf (4)) works; produce 3? I read this last night and thought that I was too tired to understand, however, I still can not understand how this is achieved. I looked through the Correction section of the companion book website for a possible typo, but nothing was specified. I also searched elsewhere, but found examples that mainly concerned strings instead of numbers. Thanks for any help. This is my first post for, so I apologize if I did something wrong in my post.
His examples:
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4));
alert(numbers.lastIndexOf(4));
alert(numbers.indexOf(4, 4));
alert(numbers.lastIndexOf(4, 4));
What I thought would be the result:
alert(numbers.indexOf(4));
//the item in the array with the fourth index, or 5
alert(numbers.lastIndexOf(4));
//5 (this was only one that seemed to make sense to me) by counting back from the last value
alert(numbers.indexOf(4, 4));
//start looking at index 4, or 5, and then count right four places to end up at 1 (last item in array).
alert(numbers.lastIndexOf(4, 4));
//1, counting back to the left from the value with index 4, or 5, to reach the first value in the array.
, , , , . .