indexOf

<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

document.write(scripts.indexOf("HTML"));
</script>
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
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
scripts[4] = "ASP";
document.write(scripts.indexOf("ASP"));
</script>
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.
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
scripts[4] = "ASP";
document.write(scripts.lastIndexOf("ASP"));
</script>
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 Reference Sort the elements of an Array
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer