0

What is the simplest way too check is some element presence to array?

I have following code:

 var val = "1";
 var arr = ["1", "2"];
 if($.inArray(val, arr)) {
 console.log("I am in!")
 } else {
 console.log("I am NOT here :( ")
 }

but it prints "1" is NOT at ["1", "2"] array! Please open my eyes - what is the problem here?

asked Nov 19, 2012 at 21:08

1 Answer 1

2

The $.inArray returns index of the matched element position which can range from 0 to (length - 1). So you should >= 0 as it is the first element it will be returning the index as 0.

var val = "1";
var arr = ["1", "2"];
if($.inArray(val, arr) >= 0) {
 console.log("I am in!")
} else {
 console.log("I am NOT here :( ")
}
answered Nov 19, 2012 at 21:09
Sign up to request clarification or add additional context in comments.

1 Comment

Very common mistake, the name implies a boolean return value.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.