how can i find the index of an item array, to find if an item is in an array using javascript

87 views Asked by At

I'm new to scripting and I was writing a script to find if a value is in an array.

/html/

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>account # a</p>

</body>
</html>

/javascript/

var cid = document.getElementsByTagName("P")[0].childNodes[0].nodeValue;

var res = cid.split(" ");

var customerid=res[2];

var abs=['a','b','c'];

var para = document.createElement("P");

var node = document.createTextNode("'"+customerid+"'");

para.appendChild(node);

document.body.appendChild(para); 

var c=document.getElementsByTagName("P")[1].childNodes[0].data;

window.alert(abs.indexOf(c));

the alert window is showing the index as -1. my plan was to use the following function if i can get the above code to get the correct index.

function check(){

if (abs.indexOf(c)>=0){

window.alert("item is in array");
}
}

check();
1

There are 1 answers

4
Mike On

.indexOf() will return -1 when the item is NOT in the array. This is because if the item is in the first index of the array, it's at index 0 since arrays are zero-based.

For your check function, as mentioned above, 0 means that the element was found in the array in the first position. So you'll want to check if .indexOf() doesn't return -1 instead of greater than 0:

function check() {
if (abs.indexOf(c) !== -1){
    window.alert("item is in array");
  }
}

You could also use the ~ shortcut:

function check() {
if (~abs.indexOf(c)){
    window.alert("item is in array");
  }
}