You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript工厂函数创建怪物攻击时生命值返回NaN问题求助

工厂函数怪物攻击后生命值NaN问题排查与修复

你的问题出在两个关键地方:

  1. 未正确调用attack方法
    在attack函数的扣血逻辑里,你写的是enemyTwo.health - enemyOne.actions.attack,这里的enemyOne.actions.attack是函数本身,不是它返回的攻击数值。用数字减去函数会得到NaN,这就是生命值异常的直接原因。

  2. 多次调用attack()导致攻击值不一致
    你在判断胜负和扣血时分别调用了attack(),每次调用都会生成新的随机攻击值,比如判断时怪物A的攻击是3,但扣血时可能变成1,这会导致逻辑混乱。

修复后的代码

function monsterFactory(type,health,skinColor,strength,weakness,sound){
  return{
    type,
    health,
    skinColor,
    strength,
    weakness,
    actions: {
      attack(){
        // 简化随机攻击值生成,替代冗余switch
        return Math.floor(Math.random()*3)+1;
      },
      scream(){
        const screams = ['Moan', 'Grumble', 'Snarl'];
        const randomIndex = Math.floor(Math.random()*3);
        console.log(screams[randomIndex]);
      },
    }
  }
}

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){
  // 提前获取双方攻击值,确保判断与扣血用同一数值
  const attack1 = enemyOne.actions.attack();
  const attack2 = enemyTwo.actions.attack();
  
  if(attack1 > attack2){
    enemyTwo.health = enemyTwo.health - attack1;
    console.log(`${enemyTwo.type} has been struck their health is now ${enemyTwo.health}`);
  }else if(attack2 > attack1){
    enemyOne.health = enemyOne.health - attack2;
    console.log(`${enemyOne.type} has been struck their health is now ${enemyOne.health}`);
  } else {
    // 补充平局场景处理
    console.log('Both monsters attack at the same time, no damage dealt!');
  }
}
attack(zombie,vampire)

关键修改说明

  • 将扣血逻辑中的函数引用改为调用后存储的数值,避免数字与函数运算产生NaN
  • 提前获取并复用双方攻击值,保证胜负判断和扣血逻辑使用同一组随机值,逻辑自洽
  • 简化了attack和scream方法的实现,去除冗余的switch语句,让代码更简洁

内容的提问来源于stack exchange,提问作者David Douglas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:10:50