地图的最后一个条目没有被删除?

时间:2019-11-28 08:46:24

标签: javascript dictionary

作为一名前锋,我正在尝试为游戏创建实体/组件/系统设计。我要尝试的第一件事是处理实体的创建和删除。我选择尝试为此使用本地地图。

由于某种原因,当我运行此代码时,我看到了预期的行为,直到到达地图的最后一个元素为止,在该元素中,看来似乎没有删除该条目时,多次调用了该更新。

代码:


class Vector{
   constructor(x, y){ this.x = x; this.y = y; }
}

class Enemy{
   constructor(id, x, y){
      this.id = id;
      this.pos = new Vector(x, y)
   }
   update(){
      this.pos.x++;
      console.log(Game.entities)
      if (this.pos.x > 10) Game.dispatch(this.id)
   }
}

const Game = {
    start: function(){
       this.entities = new Map;
       for (let i = 0; i<5; i++){
            const sid = Math.random();
            this.entities.set(sid, new Enemy(sid, i*20, 20))
       }
       this.tick(0)
    },
    dispatch: function(id){
        this.entities.delete(id)
    },
    tick: function(){
        for (let entity of this.entities.values()) {
            entity.update();
        }
        setTimeout(this.tick.bind(this), 100)
    }
}
Game.start()

预期输出:


test.js:12 Map(5) {0.5025040680322241 => Enemy, 0.42078144104682513 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(5) {0.5025040680322241 => Enemy, 0.42078144104682513 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(4) {0.5025040680322241 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(3) {0.5025040680322241 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(2) {0.5025040680322241 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}

实际输出:


test.js:12 Map(5) {0.5025040680322241 => Enemy, 0.42078144104682513 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(5) {0.5025040680322241 => Enemy, 0.42078144104682513 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(4) {0.5025040680322241 => Enemy, 0.26799686976172143 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(3) {0.5025040680322241 => Enemy, 0.7289429408250698 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(2) {0.5025040680322241 => Enemy, 0.31514175919106435 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}
test.js:12 Map(1) {0.5025040680322241 => Enemy}

1 个答案:

答案 0 :(得分:0)

我没有意识到我是在不同位置对物体进行实例化。哎呀! :(

如果在相同位置创建对象并进行相应更新,则可以正常工作。