IndexOf () and lastIndexOf () are the two methods that return the position index: All receive two parameters, where the IndexOf () method is searched backwards from the beginning of the array (position 0), and the LastIndexOf () method looks forward from the end of the array ; Returns-1 if not found.
In order to be more clear and easy to understand, the array is intentionally added several repetitions of the number:
1. indexOf ();
1) var num=[1,1,4,4,5,4,1,3,2,1];
Index:0 1 2 3 4 5 6 7 8 9
Alert (Num.indexof (1)); If you write a parameter here, you look for ' 1 ' in the NUM array, and return to the position you first found, index 0;
alert (Num.indexof); Here, if it is two parameters, it is in the NUM array from the previous back and from the 2 position to start looking for ' 1 ', and return to the position of the first find, index 6;
2) The IndexOf () method is case sensitive!
var msg= ' Hello World ';
Alert (Msg.indexof (' h ')); The IndexOf method is case-sensitive, so this returns 1;
Alert (Msg.indexof (' World ')); Including the space inside, so the return is 6;
2.lastIndexOf ();
1) var num=[1,1,4,4,5,4,1,3,2,1];
Index:0 1 2 3 4 5 6 7 8 9
Alert (Num.lastindexof (1)); 9 If you write a parameter like indexof, return the position index value, the difference is that lastIndexOf () is looking forward from the back, but the index value is constant.
Alert (Num.lastindexof)//1 Here write two parameters, refers to the position from index 2 to start looking for ' 1 ', then you first find the number ' 1 ', is at the index value of 1 position.
It's important to note that browsers that support them include ie9+, Firefox, Safari, Opera 9.5+, and Chrome.
Use of indexof and lastindeof