Check if array contains a specific element

Arrays are used to store multiple data. If we need to check that if a specific element exists in array or not and than perform rest of operations.

Let's  take an example. We have an array of names and we need to check a specific name if it exists in array or not.

var names = ["Arsenij","Vadimster","Charlie"];
function checkName() 
{
if (names.indexOf("Charlie") > -1)
alert("name exists");
else

alert
("name doesn't exists");

}

Here "Charlie" exists in array so it will show alert("name exists").

If an item doesn't exist in array indexOf will return -1 otherwise it will return the index of item in our case it will return 2;

Index of array starts from 0;

Comments

Popular posts from this blog

Using Progress Bar In C#

Get elements by class name in javascript

Jquery serer side datatables in asp.net