indexOf()
looks to see if the argument passed to the function is found in the array.
If the argument is contained in the array, the function returns the index position of the argument.
If the argument is not found in the array, the function returns -1.
Here is an example:
let names = ["David", "Cynthia", "Raymond", "Clayton", "Jennifer"]; let name = "Jennifer"; let position = names.indexOf(name); if (position >= 0) { console.log("Found " + name + " at position " + position); } else { // w w w . j av a 2 s . c om console.log(name + " not found in array."); }
lastIndexOf()
will return the position of the last occurrence of the argument in the array, or -1 if the argument isn't found.
Here is an example:
let names = ["David", "Mike", "Cynthia", "Raymond", "Clayton", "Mike", "Jennifer"]; let name = "Mike"; let firstPos = names.indexOf(name); console.log("First found " + name + " at position " + firstPos); let lastPos = names.lastIndexOf(name); console.log("Last found " + name + " at position " + lastPos);