gpt4 book ai didi

javascript - For 在 Javascript Array 3d 中

转载 作者:行者123 更新时间:2023-11-28 12:19:29 25 4
gpt4 key购买 nike

我想初始化一个 3d 数组,所有位置都为零。我正在使用for循环来填充我的矩阵,但是当我测试时,我收到错误TypeError:this.matrix[x][y]未定义我有这个:

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)

如何填充我的矩阵?

最佳答案

如果数组尚未初始化,您将必须检查数组中的每个项目,在这种情况下,您需要将其设置为 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)

关于javascript - For 在 Javascript Array 3d 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41684688/

25 4 0
文章推荐: javascript - React-Redux : how to make ReCaptcha a required field
文章推荐: javascript - 我的删除方法是拼接数组中的最后一项,而不是所选项目
文章推荐: javascript - 即使索引越界如何从数组中获取项目
文章推荐: Javascript - 根据 div 中图像的高度更改
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com