Reputation: 585
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.
Upvotes: 4
Views: 159
Reputation: 382092
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];
Upvotes: 6