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

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

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *