Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Javascript arrays sparse?

That is, if I use the current time as an index into the array:

array[Date.getTime()] = value; 

will the interpreter instantiate all the elements from 0 to now? Do different browsers do it differently?

I remember there used to be a bug in the AIX kernel, which would create pseudo-ttys on request, but if you did, say, "echo > /dev/pty10000000000" it would create /dev/pty0, /dev/pty1, .... and then fall over dead. It was fun at trade shows, but I don't want this to happen to my customers.

like image 891
Berry Avatar asked Oct 02 '09 17:10

Berry


People also ask

Are JS arrays sparse?

Why can Array s be sparse? Array s under the hood in JavaScript are Object s. Their keys are numbers, and their values are the elements. The length property on an Array takes the last element's index and adds one.

What is the difference between dense and sparse arrays?

In JavaScript, an array can be dense or sparse. An array is dense if there are items at each index starting 0 until array. length - 1 . Otherwise, if at least one item is missing at any index, the array is sparse.

Are arrays resizable in JavaScript?

C# Lists and JavaScript Arrays are basically the same when the JavaScript array has no holes. Both are resizable arrays.

Can arrays have gaps?

You see, JavaScript arrays are not quite like those of more restrictive languages such as Java, in that they are sparse arrays. That means that they can contain gaps between elements, gaps where the unwary can fall through or be swallowed up by bugs!


1 Answers

Yes, they are. They are actually hash tables internally, so you can use not only large integers but also strings, floats, or other objects. All keys get converted to strings via toString() before being added to the hash. You can confirm this with some test code:

<script>   var array = [];   array[0] = "zero";   array[new Date().getTime()] = "now";   array[3.14] = "pi";    for (var i in array) {       alert("array["+i+"] = " + array[i] + ", typeof("+i+") == " + typeof(i));   } </script> 

Displays:

array[0] = zero, typeof(0) == string array[1254503972355] = now, typeof(1254503972355) == string array[3.14] = pi, typeof(3.14) == string 

Notice how I used for...in syntax, which only gives you the indices that are actually defined. If you use the more common for (var i = 0; i < array.length; ++i) style of iteration then you will obviously have problems with non-standard array indices.

like image 122
John Kugelman Avatar answered Oct 28 '22 06:10

John Kugelman