javascript item splice self out of list

前端 未结 5 1448
慢半拍i
慢半拍i 2021-02-20 11:46

If I have an array of objects is there any way possible for the item to splice itself out of the array that contains it?

For example: If a bad guy dies he will splice hi

5条回答
  •  有刺的猬
    2021-02-20 12:31

    You can also use an object and instead of splice, delete the enemy:

    var activeEnemies = {};
    
    function Enemy() {
      this.id = Enemy.getId(); // function to return unique id
      activeEnemies[this.id] = this;
      // ....
    }
    
    Enemy.getId = (function() {
      var count = 0;
      return function() {
        return 'enemyNumber' + count++;
      }
    }());
    
    Enemy.prototype.exterminate = function() {
      // do tidy up
      delete activeEnemies[this.id];
    }
    
    Enemy.prototype.showId = function() {
      console.log(this.id);
    }
    
    Enemy.prototype.showEnemies = function() {
      var enemyList = [];
      for (var enemy in activeEnemies) {
        if (activeEnemies.hasOwnProperty(enemy)) {
          enemyList.push(enemy);
        }
      }
      return enemyList.join('\n');
    }
    
    var e0 = new Enemy();
    var e1 = new Enemy();
    
    console.log( Enemy.prototype.showEnemies() ); // enemyNumber0
                                                  // enemyNumber1
    
    e0.exterminate();
    
    console.log( Enemy.prototype.showEnemies() ); // enemyNumber1
    

提交回复
热议问题