Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Trying to contain objects inside dynamic properties

I have a function that creates an object and saves it as an ID in another object:

var enemyList = {}; //global var

Enemy = function () {
  var id = Math.random(); //random id
  var enemy = {
    some properties
  };
  enemyList.id = enemy;
}

Now, I found 'for loop' while searching online and I edited in order to update every id which contain an enemy object ref:

setInterval(update, 40); //execute update all the time
var frameCount = 0; //global var

function update {
  if (frameCount % 100 === 0) //  spawns new enemy every 4 seconds
    Enemy();

  for (var key in enemyList) {
    enemyList.key.update(); //move them around...     
  }
}

Every 4 seconds a new enemy is created, then that loop is supposed to move each enemy according to some logic... the thing is, once a new enemy is created, it replaces the old enemy, moves around and then is replaced by the next spawned enemy even though it shouldn't since they have unique ids. Why does it happen? Thank you for your time.

like image 623
RunningFromShia Avatar asked Mar 21 '26 08:03

RunningFromShia


1 Answers

When you say

enemyList.id = enemy;

you are actually setting the enemy object to the id property of enemyList object, you are not creating a new property with the value of id. It should have been

enemyList[id] = enemy;

The same is applicable for the for loop as well.

enemyList[key].update();

Additional suggestions:

  1. The for..in will get all the enumerable, inherited properties of the enemyList object, not just the properties on it. So, it is not quite normal to have an if condition around in it, like this

    for (var key in enemyList) {
      if (enemyList.hasOwnProperty(key)) // make sure it is the own property
        enemyList.key.update();          // move them around...
    }
    
  2. setInterval(update, 40); means that the update will be executed every 40 milliseconds, not 4 seconds. So, it should have been setInterval(update, 4000);

like image 197
thefourtheye Avatar answered Mar 24 '26 01:03

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!