适用于Javascript Array 3d

时间:2017-01-16 20:42:42

标签: javascript arrays

我希望在所有位置初始化一个带有零的数组3d。我正在使用TypeError: this.matrix[x][y] is undefined来填充我的矩阵但是当我测试时,我收到错误class Cube { constructor(size) { this.size = size this.matrix = [ [ [] ], [ [] ] ] this.createMatrix(size) } getsize() { return this.size } /*Fill matrix with zeros*/ createMatrix(size) { for (var x = 0; x < size; x++) { for (var y = 0; y < size ; y++) { for (var z = 0; z < size ; z++) { this.matrix[x][y][z] = 0 } } } console.log(this.matrix) } } myCube = new Cube(4) 我有这个:

every second

如何填写矩阵?

3 个答案:

答案 0 :(得分:2)

那是因为你需要初始化每个单独的数组。请记住:3D数组是数组的数组 数组

function threeDArray(width, height, depth) {
  var result = [];
  for (var x = 0; x < width; x++) {
    result[x] = [];
    for (var y = 0; y < height; y++) {
      result[x][y] = [];
      for (var z = 0; z < depth; z++) {
        result[x][y][z] = 0;
      }
    }
  }
  return result;
}

console.log(threeDArray(3, 3, 3));

答案 1 :(得分:2)

如果尚未初始化,则必须检查数组中的每个项目,在这种情况下,您需要将其设置为Array

&#13;
&#13;
class Cube {

  constructor(size) {
    this.size = size
    this.matrix = [ ]
    this.createMatrix(size)
  }

  getsize() {
    return this.size
  }

  /*Fill matrix with zeros*/
  createMatrix(size) {
    for (var x = 0; x < size; x++) {
      for (var y = 0; y < size ; y++) {
        for (var z = 0; z < size ; z++) {
          if (!Array.isArray(this.matrix[x])) {
            this.matrix[x] = []
          }
          if (!Array.isArray(this.matrix[x][y])) {
            this.matrix[x][y] = []
          }
          if (!Array.isArray(this.matrix[x][y][z])) {
            this.matrix[x][y][z]= []
          }
          this.matrix[x][y][z] = 0
        }
      } 
    }
    console.log(this.matrix)
  }
}

myCube = new Cube(4)
&#13;
&#13;
&#13;

答案 2 :(得分:2)

您可以使用Array.from({ length: n })创建n长度的空数组,并使用fill()方法填充零:

const emptyArray = n => Array.from({ length: n });

const createMatrix = n => emptyArray(n).map(() =>
  emptyArray(n).map(() => emptyArray(n).fill(0))
);

console.log(createMatrix(4));