I just want to understand how Javascript arrays work but I have a complicated problem here.
First I created my array:
var arr = [];
And set some elements in it:
arr[5] = "a thing";
arr[2] = undefined;
I thought that I should have an array of size 2, because I only have two objects at 2 specific indexes. So I tested it with the .length property of arrays:
document.write(arr.length + "<br>");
The result, interestingly, is 6. But it must contain two items. How can its size be 6? It is probably related with the latest index that I used, here arr[5] = "a thing";
I then tried to loop over it:
var size = 0;
for(var x in arr){
size++;
}
And the size variable is now 2. So, what I learned from this: if I use a for in loop, I will calculate how many properties are in it, not its last index.
But if I try to document.write(arr[4]) (which is not set yet), it writes undefined.
So why is arr[2] counted in the for..in loop, but not arr[4]?
Let me answer my question: what I was thinking about typeof undefined == undefined which is amazingly true. But this is JavaScript, we need to play with it using his own rules :)
jsFiddle and snippet below.
var arr = [];
arr[5] = "a thing";
arr[2] = undefined;
document.write(arr.length + "<br>");
var size = 0;
for(var x in arr){
size++;
}
document.write(size + "<br>");
document.write(arr[4] + "<br>");