Lurkers; Cannot Read Error, 'Undefined'

For some reason I am getting the following error:

Type error, cannot read property ‘type’ of undefined.

However, everything looks defined to me…

var enemies = hero.findEnemies();
var enemyIndex = 0;

// Wrap this section in a while loop to iterate all enemies.
// While the enemyIndex is less than the length of enemies
while (enemyIndex < enemies.length) {
var enemy = enemies[enemyIndex];
if (enemy.type == 'shaman') {
    while (enemy.health > 0) {
        hero.attack(enemy);
    }
}

How do you know if the enemy exists? You need to check it first before attacking the shaman. (maybe they were killed after you searched for them)

I think I am missing it still. I have an ‘if’ statement, which should take care of that, right? And the ‘if’ statement is attached to the array enemies, which does the searching. So, I am not sure where the break down would be in not being able to find or store the information for the enemy…

For example you have enemies[0]. Its type is shaman, so you attack it. During the time you took to kill the shaman the enemies array may not be actual anymore, as some shamans could have been killed by accident. Then you go to enemies[1], and it turns out that it’s already dead - and the error pops up. You also forgot to increase the enemyIndex, by the way.