I want initialize an array 3d with zeros in all positions. i am using a for cycle
for filling my matrix but when I tested, I get an error TypeError: this.matrix[x][y] is undefined
I have this:
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)
How Can I fill my matrix?
That's because you need to initialize each individual array. Remember: a 3D array is an array of arrays of arrays .
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));
You will have to check every item in the array if it wasn't initialized yet, and in such case you will need to set it to Array
:
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)
You can use Array.from({ length: n })
to create empty arrays of n
length, and fill them with zeros using the fill()
method:
const emptyArray = n => Array.from({ length: n }); const createMatrix = n => emptyArray(n).map(() => emptyArray(n).map(() => emptyArray(n).fill(0)) ); console.log(createMatrix(4));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.