Search code examples
javascriptarrayssparse-matrix

Are Arrays really "sparsed" in JavaScript by default?


Are Arrays really "sparsed" in JavaScript by default?

How to delete single array element with no index shift?

What is the difference between:

var a = new Array(10);
var b = new Array(2);

Do these Arrays occupy different space in memory? Can I turn Array(2) into Array(10) and back?

UPDATE 1

The following code

<body>
<script type="text/javascript">

    var a = new Array(10);
    var b = new Array(2);

    document.write('a[5] is ' + a[5] + '<br/>');
    document.write('a[15] is ' + a[15] + '<br/>');
    document.write('a.length is ' + a.length + '<br/>');
    document.write('b[5] is ' + b[5] + '<br/>');
    document.write('b[15] is ' + b[15] + '<br/>');
    document.write('b.length is ' + b.length + '<br/>');

    b[9]=12;
    delete b[9];

    document.write('After resize...<br/>');
    document.write('b[5] is ' + b[5] + '<br/>');
    document.write('b[15] is ' + b[15] + '<br/>');
    document.write('b.length is ' + b.length + '<br/>');

</script>
</body>

will return

a[5] is undefined
a[15] is undefined
a.length is 10
b[5] is undefined
b[15] is undefined
b.length is 2
After resize...
b[5] is undefined
b[15] is undefined
b.length is 10

So, I made b have the same properties as a. Can I do this without assigning fake value to b[9]? Can I do revers, i.e. having a.length being 2?


Solution

    1. Yes, arrays are sparse by default. Their properties aren't even defined. You can test it with this code:

      var arr = new Array(10);
      for(var x in arr) {
          alert(x); // Never alerts a number
      }
      
    2. To delete a single element, use delete:

      delete arr[5]; // Deletes element 6.
      
    3. Memory is likely irrelevant, and different engines will handle it differently. I don't think that can be answered accurately. As for changing dimensions, JavaScript arrays don't have fixed dimensions. This is perfectly legal:

      var arr = new Array(2);
      arr[5] = "Hello!";
      

    You can read more about JavaScript in general on http://developer.mozilla.com/. Arrays are just objects with some extra special properties. It doesn't really have indexes so much as keys.