【问题标题】:2 dimensional array of class objects in JavascriptJavascript中类对象的二维数组
【发布时间】: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


【解决方案1】:

我在 cmets 中写的一个例子

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 = [];

for (let i = 0; i < 11; i++) {
  for (let j = 0; j < 11; j++) {
    boxes[i] = [...(boxes[i] ? boxes[i] : []),
      new Box(i, j, i, j, "Test")
    ];
  }
}

console.log(boxes[3][3].getHeight());
console.log(boxes[4][6].getHeight());

【讨论】:

  • 这行得通!谢谢你。我只能给你打勾,因为我是新来的,所以它不会出现在号码上。我必须看看问号和省略号在做什么。
  • @JohnG 他们是ternary operators
  • @JohnG 基本上是(if this ? then this : else this)
  • @JohnG ...spread operator
【解决方案2】:

据我了解,您已经声明了一个类框,并且您想要创建该类的对象数组。考虑到这种情况, 你的代码有语法错误:数组和循环必须在类定义之外。

既然你想创建一个对象数组,它不是一个二维数组,它只是一个一维数组。所以代码应该是这样的

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 = [];

for(let i = 0; i < 11; i++){
       boxes.push(new Box(i,i+2,i,i+2,"Test"));
}

for(var cnt in boxes)
  console.log(boxes[cnt]);

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2013-01-02
    • 1970-01-01
    • 2014-06-11
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多