In fact, you can call the constructor and pass zero or more parameters. When you don’t pass any, then you’ll end up with a new empty array (this is the example we’ve met in the previous post). You can also pass a single parameter to the array. When you do that, two things can happen:
- passing a number creates a new array and sets its length property to that value (notice that the array is still empty; the difference is that it the length property isn’t zero);
- passing a non-number value is the same as creating a new empty array and pushing that item into that new array.
Here’s some code that illustrates both usages:
var arr = new Array(10);//initiate array and set length = 10 var arr2 = new Array(1, 2, 3); alert(arr.length); //prints 10 alert(arr2.length); //prints 3
Notice that setting the length might introduce some “ambiguities”. For instance, what happens when you run the following code:
Since when we initialized arr we set the length to 10, then push will put the current item (in this case, 12) on position 11 (10, if you’re counting from 0). this might not be intuitive,but it’s how it works.
Notice that if you pass a single non numeric parameter to the array,you’re, in fact, creating a new array which contains only that element:
var arr3 = new Array(''10''); alert(arr3.length); //prints 1 alert(arr3);//prints string 10