0

I am trying to check if user code exist in array. But the jQuery code is returning false even when the code exist in array.

function isValidCode(code){
  var arr = [1, 2, 3];
  //return ($.inArray(code, arr) > -1);
  return ($.inArray(code, arr) !== -1);
}

function LuckWinner(key){
  if(isValidCode(key)){
    console.log(key+ ": is in array");
  } else {
    console.log(key+" is NOT in array");
  }
}
George
  • 35,662
  • 8
  • 61
  • 98
Peter
  • 1,625
  • 1
  • 17
  • 39

1 Answers1

2

Your code seems to be working just as expected.

Note that $.inArray() will perform a type comparison; I expect you are passing a string. If you are testing for a key that is a string, your isValidCode function will return false, as your array only contains integer values. You can cast the code to an integer with parseInt to avoid this issue:

function isValidCode(code){
    var arr = [1, 2, 3];

    return ($.inArray( parseInt( code, 10 ), arr ) !== -1);
}
George
  • 35,662
  • 8
  • 61
  • 98