Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Array is not empty but size is 0

I create a array in Javascript. I want to use the array for key-value pair.

I can successfully add new items and delete items but the length of it is always 0.

Actually the problem I faced is when I want to convert it to a JSON string, it shows empty string: "[]". I just wonder if they are related. And I would also want to know why I cannot convert it.

Below is the debug information, It show the array contain 3 objects but the length is 0. The browser is Firefox 44.0 for Ubuntu.

Thanks!

Array with length <code>0</code> and properties <code>1454073967313</code>, <code>1454073968645</code>, and <code>1454073969737</code>


Fellow @georg idea, I limited the index into 1000 and leave the rest code as before. Everything works including the JSON part. The next picture shows that in my array, there are actual 4 elements, the maximum index is 805.

enter image description here

One thing I learned is that the length of Javascript Array is not the real size but the maximum index number.

The newest finding, the array is really as long as the largest index number. The rest of the element is Null.

like image 698
Pingjiang Li Avatar asked Jan 29 '16 13:01

Pingjiang Li


1 Answers

This is one of many oddities in javascript.

> a = []
[]
> a[4294967295] = 1
1
> a.length
0 // wtf?

The problem is that Array.length is limited to 32 bits, so its max value is 2^32-1 = 4294967295. If you provide an index greater than or equal to 4294967295, the engine creates a new entry in the array, as usual, but refuses to update its length - without throwing any error. So you end up with a bag of properties, and the length equal to 0.

As others suggested, you will be better off using objects if you have such large numeric indexes.

like image 58
georg Avatar answered Oct 05 '22 10:10

georg