【问题标题】:Is there a class array? [duplicate]有类数组吗? [复制]
【发布时间】:2021-09-10 07:40:41
【问题描述】:

我正在制作一个平台游戏,我想知道是否有一种更简单的方法可以将对象存储在数组中,因为我使用数组来检查碰撞。 一个类可以自动拥有任何类型的数组吗?

//This is with making my own array
var obstacleArray = [];
class Obstacle {
    constructor(x, y) {
        this.x = x,
        this.y = y,
        this.width = 50,
        this.height = 50
    }
    
    addToArray() {
        obstacleArray.push(this);
    }
}
obstacle1 = new Obstacle(0, 0);
obstacle2 = new Obstacle(50, 0);
obstacle1.addToArray();
obstacle2.addToArray();
for (let i = 0; i < obstacleArray.length;i++) {
    //check for collision
}

对于一个类拥有的许多变量,是否有某种内置数组,这样我就可以快速检查碰撞,而不必为每个障碍物调用 addToArray 函数?

【问题讨论】:

  • 我还不太了解工厂,请您详细介绍一下或者举例说明工厂是什么?将不胜感激谢谢!
  • 你总是可以搜索短语 javascript factory pattern - 那里有很多很好的教程......当然,你可以在构造函数中使用obstacleArray.push(this);跨度>
  • 另外,我建议使用 static 类变量,而不是“外部”数组...。将所有内容放在一起
  • "是否有某种内置数组" - 没有,这是件好事:它会阻止垃圾收集。

标签: javascript arrays class for-loop collision


【解决方案1】:

你总是可以在构造函数中推送到数组

工作完成:p

可选但我推荐它:使用类static 来保存数组

class Obstacle {
    static obstacleArray = [];
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 50;
        this.height = 50;
        Obstacle.obstacleArray.push(this);
    }
}
obstacle1 = new Obstacle(0, 0);
obstacle2 = new Obstacle(50, 0);
console.log(Obstacle.obstacleArray);

另一个有趣的选择可能是使用 Set 而不是数组

class Obstacle {
    static obstacles = new Set;
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 50;
        this.height = 50;
        Obstacle.obstacles.add(this);
    }
    remove() {
        Obstacle.obstacles.delete(this);
    }
}
obstacle1 = new Obstacle(0, 0);
obstacle2 = new Obstacle(50, 0);
[...Obstacle.obstacles.keys()].forEach(obstacle => {
    console.log(obstacle.x);
});
// you can remove an obstacle easily
console.log('removed 1');
obstacle1.remove();
[...Obstacle.obstacles.keys()].forEach(obstacle => {
    console.log(obstacle.x);
});

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2020-07-19
    • 2023-04-02
    • 2013-04-11
    • 2014-11-01
    • 2019-05-28
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多