Home > Net >  NaN result from function
NaN result from function

Time:09-12

this is my first post. I am practicing function and factory function in Javascript. I created two monster and a function for them to attack each other and adjust their health. When the attack function runs and logs a statement to the console, the value of the monsters new health returns as NaN. I have tested with typeof to ensure that health and the attack are both numbers, but can't get the new health number to appear.

function monsterFactory(type,health,skinColor,strength,weakness,sound){
  return{
    type,
    health,
    skinColor,
    strength,
    weakness,
    actions: {
      attack(){
        const randomAttak = Math.floor(Math.random()*3) 1;
        switch(randomAttak){
          case 1:
          return 1;
          break;
          case 2:
          return 2;
          break;
          case 3:
          return 3;
          break;
        }
      },
      scream(){
        const randomScream = Math.floor(Math.random()*3) 1;
        switch(randomScream){
          case 1:
          console.log(`Moan`);
          break;
          case 2:
          console.log(`Grumble`);
          break;
          case 3:
          console.log(`Snarl`);
          break;
        }
      },
    }
  }
}

const zombie = monsterFactory('Zombie',5,'Grey','Feels no pain','Slow','moan')
console.log(zombie.health)

const vampire = monsterFactory('Vampire',5,'White','Immortal','Sunlight','Hiss')
console.log(vampire.actions.attack()>zombie.actions.attack())


function attack(enemyOne,enemyTwo){
  if(enemyOne.actions.attack() > enemyTwo.actions.attack()){
    enemyTwo.health = enemyTwo.health - enemyOne.actions.attack
    console.log(`${enemyTwo.type} has been struck their health is now ${enemyTwo.health}`)
  }else if(enemyTwo.actions.attack()>enemyOne.actions.attack()){
    enemyOne.health = enemyOne.health - enemyOne.actions.attack
    console.log(`${enemyOne.type} has been struck their health is now ${enemyOne.health}`)
  }
}
attack(zombie,vampire)

CodePudding user response:

In your attack function, you use enemyOne.actions.attack. However, that is just a reference to the function itself, and doesn't run the function, hence the NaN value. To fix it, just make sure to run the function.

Fixed attack() function:

function attack(enemyOne,enemyTwo){
  if(enemyOne.actions.attack() > enemyTwo.actions.attack()){
    enemyTwo.health = enemyTwo.health - enemyOne.actions.attack()
    console.log(`${enemyTwo.type} has been struck their health is now ${enemyTwo.health}`)
  }else if(enemyTwo.actions.attack()>enemyOne.actions.attack()){
    enemyOne.health = enemyOne.health - enemyOne.actions.attack()
    console.log(`${enemyOne.type} has been struck their health is now ${enemyOne.health}`)
  }
}
  • Related