Hoping someone can shed some light on this simple piece of code not working as expected:
var arr = new Array(10);
arr.length; // 10. Why? Very wierd.
Why does it return 10?
Hoping someone can shed some light on this simple piece of code not working as expected:
var arr = new Array(10);
arr.length; // 10. Why? Very wierd.
Why does it return 10?
I makes an Array with 10 cells... so it returns 10 :)
You wanted to do:
var arr = [10]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number
So it is impossible to create a new array with only one number element using the new
keyword.
You can however do :
var arr = [10]; // Creates a new array with one element (the number 10)
console.log(arr.length); // displays 1 because the array contains one element.
It returns 10, because you give only one integer, as argument, to the Array constructor. In this case, the new Array constructor is acting like some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions. An example of this in Java:
int[] a = new int[10];
Or C#:
int[] array = new int[5];
In Javascript, when you write:
var a = new Array(10);
a[0] // returns undefined
a.length // returns 10.
and if you write:
a.toString() // returns ",,,,,,,,,", a comma for each element + 1
But, since Javascript doesn't need to allocate memory for an array, is better to use use the [] constructor:
var a = [10];
a[0] //returns 10
a.length //returns 1
I think that the thing that confuse all the people is this:
var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5
But you can do the same in this way:
var a = [1,2,3,4,5];
a[0] // returns 1
a.length // returns 5
So, in conclusion, try to avoid using the new Array constructor, and use the [] constructor instead.