4

jQuery inArray returns -1 if the array contains single element.

var a = Array(1);
console.log($.inArray(1,a));

This returns -1. But if the array contains 2 or more elements it works perfectly.

var a = Array(1,2,3);
console.log($.inArray(1,a));

Returns perfect position.

4
  • 1
    Good question Thanks we are all understood Commented May 5, 2014 at 12:24
  • @sudharsan have you upvoted this..? :) Commented May 5, 2014 at 12:26
  • 1
    this is confidential i didn't tell Commented May 5, 2014 at 12:27
  • @sudharsan oh.. :) Then i too wont tell you that i had upvoted this question and answer as well.. Commented May 5, 2014 at 12:28

1 Answer 1

6

Contrary to what you seem to think, Array(1) doesn't create an array with element 1 but an array of size 1. That's a specific behavior you get when you pass only one argument and it's an integer.

From the MDN :

If the only argument passed to the Array constructor is an integer between 0 and 2^32-1 (inclusive), this returns a new JavaScript array with length set to that number.

You should probably almost never use this Array constructor whose strange behavior leads to many bugs and which is mostly useless. Use this :

var a = [1];
Sign up to request clarification or add additional context in comments.

6 Comments

never (or almost never) use the Array constructor. what is the reason for that..?
@RajaprabhuAravindasamy 1) its behavior is far too surprising. 2) it's mostly useless
Then how its returning perfect position with this: var a = Array(1,2,3);
@ShashikumarMisal he explained that in his post. read carefully with patience.
@ShashikumarMisal Because then it's equivalent to [1,2,3]. Read the document I link to.
|

Your Answer

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.