The output of above code is 3 ( staring from 0 for PHP , HTML is 3rd element )
We can search an array by using indexOf function in JavaScript. If the element is present inside the array then we will get the position of the element. If not present then the function will return -1. Here is the syntax .
array.indexOf('search_string');
If we search for SQL and we will get the output as -1 ( as this element is not present inside array )
Searching from the start
If we have same element at two different places then indexOf will return the position of fist matching starting from the start of the array. ( not from end ). This code will explain that
The output is 1. The element ASP is present at two places, starting from beginning it is at 1st position ( PHP is 0 position ) .
lastIndexOf
We can search and if found get the position of the element inside Array by using lastIndexOf function. The difference between indexOf and lastIndexOf is searching the array starts from end in later case.
Here is an example.
The output of above code is 4 as ASP is there in 4th position ( PHP is 0 position). Note that lastIndexOf() starts searching from the end of the array so it got the search string at 4th position. Same way if we use indexOf function we would have got 1 as output.
← Array ReferenceSort the elements of an Array → ← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
plus2net.com
✖
We use cookies to improve your browsing experience. . Learn more