0

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 Answer 1

1

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),
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

?? This works. It initializes all the arrays it needs exactly once. The arrays are not sparse.
Disregard my previous. Good approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.