【发布时间】:2018-12-16 08:27:02
【问题描述】:
试图在 JS 中创建一个类对象数组。我不知道 Javascript 如何处理这个问题,但不是 10x10 网格,而是所有数字都设置为 10,而不是我要分配的 i 和 j 值。
class Box {
constructor(width, height, x, y, inside) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.inside = inside;
}
getHeight() {
return this.height;
}
setHeight(newHeight) {
this.height = newHeight;
}
let boxes = [
[]
];
let testBox = new Box(1, 1, 1, 1, "Test")
for (let i = 0; i < 11; i++) {
for (let j = 0; j < 11; j++) {
boxes[i[j]] = new Box(i, j, i, j, "Test");
}
}
console.log(testBox.getHeight()); //Working Example
console.log(boxes[3[3]].getHeight()); //outputs 10?
console.log(boxes[4[6]].getHeight()); //outputs 10?
【问题讨论】:
-
D2 数组只是数组中的数组,因此您需要像这样访问它们
boxes[3][3] -
在使用 js 时,如果出现问题,您的第一反应应该是检查控制台。正如您这次看到的那样,您会收到一个错误。
-
感谢您的回复。我一直在尝试,但它导致浏览器抱怨“未捕获的类型错误:无法读取未定义的属性 '3'”。所以我在尝试 [[]] 语法。
-
那么你并没有做你认为的那样 - 再次,控制台是你的朋友。
-
不,在我将其更改为您建议的访问方式之前,它不会出错。
标签: javascript arrays dimensional