Trying to for each towers



  • I'm trying to write a `for each` for my towers.

    var towers = Game.rooms[roomName].find(FIND_MY_STRUCTURES, {filter: {structureType: STRUCTURE_TOWER}});
    console.log(towers.length); // Gives me 2, correct
    for (var tower in towers) {

        console.log(tower); // Gives me 0 then 1
        console.log('Pos: ' + tower.pos); // Gives me `Pos: undefined`

    }

    I wanted to put this in the for loop:

    var closestDamagedStructure = tower.pos.findClosestByRange(FIND_STRUCTURES, {
    filter: (structure) => structure.hits < structure.hitsMax
    });

    But since tower.pos is undefined, that fails.



  • for (var tower in towers) {
    // ...
    }

    gives you the structure's index within the tower's array.

    Try something like this:

    for (var id in towers) {
    var tower = towers[id];
    // ...
    }