1
var x = new Array(10);
$.inArray(10,x);
#Returns -1

Fiddle

I've come across this weird issue, checking a value in an array with $.inArray, really simple.

But, if the array only has one value in it, inArray returns -1. If I add another value to the array, it works as expected.

This only happens with integers and not with strings.

What's going on?!

2
  • 6
    You just created an array with a length of 10, not an array that contains the value 10, see the DOCS Commented Dec 27, 2012 at 21:29
  • 1
    Tip: 1. console.log( x ) 2. check empty array in console Commented Dec 27, 2012 at 21:34

3 Answers 3

4

If you want to create an array with the one number(10) inside you should use bracket literal:

var x = [10];
$.inArray(10,x);

Or with push:

var x = new Array();
x.push(10);

Obviously the first one is more readable and faster to write.

A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. Note that this special case only applies to JavaScript arrays created with the Array constructor, not with array literals created with the bracket syntax.

If the only argument passed to the Array constructor is an integer, a new, empty JavaScript array and its length is set to that number MDN

Fixed fiddle

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

Comments

1

I suggest to check documentation for arrays in JavaScript, link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array

In your case, by using:

var x = new Array(10);

It creates an array with length 10 and each item of the array is undefined

I suggest to use:

var x = [10];

this is an array with one item at index 0 that has value 10.

Comments

0

var x = new Array(10); creates an array with 10 slots, not an array that contains "10"

Comments

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.