1

So I've got an array in javascript and want to see if a value exists in it... though it's returning false even though 120 does exist in the array. I've written my own method to handle this in the meantime though just wanted to see if anyone else can see what I'm doing wrong here?

var myArray = [120, 121, 222];

if (jQuery.inArray(120, myArray)) {
    alert("in my array");
} else {
    alert("not in array");
}

jsFiddle - http://jsfiddle.net/453ebncs/

0

1 Answer 1

3

Because jQuery.inArray return -1 or position (in your case it will be 0) and 0 is false, you need check >= 0

var myArray = [120, 121, 222];
if (jQuery.inArray(120, myArray) >= 0) {
   alert("in my array");
} else {
   alert("not in array");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.