#javascript
#JavaScript / Object / Array.indexOf(), Array.lastIndexOf() - methods that return the position (index) of the matching element
.indexOf()
.indexOf() is a method that returns the index of the element that matches the given value.
Grammar
array. indexOf( value, start )
- value: Enter the value to search for.
- start : The index value to start searching. Optional, if omitted the value is 0.
- Returns the index if there is a matching element. If multiple, returns the index of the first element. Returns -1 if not.
example
Array element indices start from 0. That is, the index of the first element is 0 and the index of the second element is 1.
[ 'a', 'b', 'c', 'd' ].indexOf( 'a' )
Returns 0, the index of string a.
[ 'a', 'b', 'c', 'd' ].indexOf( 'b' )
Returns 1, the index of string b.
[ 'a', 'b', 'c', 'c' ].indexOf( 'c' )
If there is more than one string c, returns index 2 of the first element.
[ 'a', 'b', 'c', 'd' ].indexOf( 'f' )
Returns -1 because there is no string f.
[ 'a', 'b', 'a', 'c' ].indexOf( 'a', 1 )
Search string a from 1 index. So it returns 2.
[ '1', 1, 'a', 'b' ].indexOf( 1 )
Look for the same data type. returns 1.
.lastindexOf()
.lastIndexOf() searches backwards unlike .indexOf() .
grammar
array. lastIndexOf( value, start )
- value: Enter the value to search for.
- start : The index value to start searching. It can be omitted, if omitted, it will search from the end.
- Returns the index if there is a matching element. If there are multiple matching elements, returns the index of the last element. Returns -1 if not.
example
document. write( [ 'a', 'a', 'b', 'c', 'd' ]. indexOf( 'a' ) );
.indexOf() returns 0, the index of the first occurrence of string a when searching from the front.
document.write( [ 'a', 'a', 'b', 'c', 'd' ].lastIndexOf( 'a' ) );
.lastIndexOf() returns 1, the index of the first occurrence of string a when searching backwards.