views:

32

answers:

1

I am trying to populate a dynamic 3 dimensional array so I don't have to type it all out

var o = {
  matrix: (function(n) {
    for (var x = 0; x < n; x ++) {
      for (var y = 0; y < n; y++) {
        for (var z = 0; z < n; z++) {
          this[x][y][z] = -1;
        }
      }
    }
  }).call(Array, 5),
  ...
}

The message I get is Uncaught TypeError: Cannot read property '0' of undefined

Any help ... please? :(

+1  A: 

There's no explicit multi-dimensional array support in JavaScript, just arrays of arrays. You need to initialize the arrays before populating them:

var o = {
  matrix: (function(a, n) {
    for (var x = 0; x < n; x++) {
      a[x] = [];
      for (var y = 0; y < n; y++) {
        a[x][y] = [];
        for (var z = 0; z < n; z++) {
          a[x][y][z] = -1;
        }
      }
    }
    return a;
  })([], 5),
  ...
}
Tim Down
?? This works. It initializes all the arrays it needs exactly once. The arrays are not sparse.
Tim Down
Disregard my previous. Good approach.
g.d.d.c