-2

I want to check if an Array contains a value. I tried this, but it doesn't work:

var accountList = [3, 4];
function isInArray(value, array) {
    return array.indexOf(value);
}

if (isInArray(4, accountList) > -1) {
    document.getElementById("pp").innerHTML = "found";
}

I want to use this to check if an input (value) is inside an Array. I use the 3, 4 value just for trying this method.

I already tried searching in other topic but I don't resolve my problem.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Frank
  • 125
  • 1
  • 2
  • 8
  • 2
    Possible duplicate of [Determine whether an array contains a value](http://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) – Laerte Jan 14 '16 at 13:56
  • Try to add the script at the bottom (see answer). – rishabh dev Jan 14 '16 at 14:27

3 Answers3

1
var accountList = [3,4];
function isInArray(value, array){
    var i;
    for(i = 0; i < array.length; i = i + 1) {
      if (array[i] === value) {
         return true
      }
    }
} 

if(isInArray(4, accountList)){
    document.getElementById("pp").innerHTML = "found";
}`
Leguest
  • 2,097
  • 2
  • 17
  • 20
0

It works
Possible mistakes may be you are adding script on top of page i.e. in head. In this case document.getElementById("pp") would not work because body have not loaded at the time of execution. Try adding the script after the last element of the body or document.onload callback.

var accountList = [3, 4];

function isInArray(value, array){
    return array.indexOf(value);
}

if(isInArray(4, accountList) > -1){
    document.getElementById("pp").innerHTML = "found";
}
<p id="pp">
  </p>
rishabh dev
  • 1,711
  • 1
  • 15
  • 26
-2
var accountList = [3,4];

if (accountList.length > 0) {
// has value
}
else {
//empty;
}
  • I think you misundertood his question. He wants to know if the array contains a certain value, and not if it contains any value. – Laerte Jan 14 '16 at 14:22