Single element array initialization with an integer value (javascript)

When initializing a javascript array (with a known number of its elements), one does normally write a simple line of code:

var myArray = new Array("string1", "string2", 123);

This works fine when we have more than one element of the array. However, when we want to declare an array with one element, and the element is of an integer type, we could encounter an odd behavior. The reason behind is that a following command:

var mySecondArray = new Array(12);

…initializes an array with twelve elements, which aren’t filled at this time. And not, as expected, a single-element one. So, in order to declare a single-element array with an integer value, let’s consider a following “workaround”:

var myThirdArray = new Array(1);
myThirdArray[0] = 12;

Declaring an array with a length of 1 element, then assigning the value of the element by finding it by its index should solve the problem.

Best regards,

lukasz

~ by Łukasz on 8 February 2010.

2 Responses to “Single element array initialization with an integer value (javascript)”

  1. Thanks alot …. I used this method in my project..

  2. Great, but how can i do to pass an array of 1 int as parameter to a function? Thanks for your lights!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: