将对象从函数工厂推入数组

Pushing Objects From Function Factories into Arrays

我做了两个函数工厂,一个给僵尸,一个给人类。我想要一个函数来计算僵尸总生命值与人类攻击总值之间的差异。它每个都适用,但我不能全神贯注于如何进行多人对抗僵尸。我曾尝试将人类对象推入一个数组,以便我可以总结所有攻击(我会重复僵尸),但没有运气......

//Create a Human spawning object
var humanArr = [];
const humanSpawns = (attack) => {
    let human = {
        attack: attack
    };
    humanArr.push(human);
};


//Create a Zombie spawning object
const zombieSpawns = (health) => {
    return {
        health: health
    }
};


//Create function to have humans and zombies fight
function fight() {
   var result = humanOne.attack - zombieOne.health;
   if(result > 0) {
       document.write('Live to see another day.');
   } else {
       document.write('The zombies are taking over!');
   }
}

const zombieOne = zombieSpawns(12);
const humanOne = humanSpawns(11);
fight();

尝试类似于我的代码片段的方法,您真正需要的是一种创建单元的方法。 我使用了普通对象,但是如果你想 return casualties 比方说,你需要 return 每个主对象 humanoids 的数组,并且 splice他们在战斗中基于受到的伤害。放轻松,你会看到你的军队战斗!

我追求的逻辑:

  1. 我需要一支军队!

    1.1。要创建一支军队,首先我需要一些单位,所以我建立 createHumanoid(应该将其重命名为 createArmy)

    1.2。 createHumanoid 将帮助设置单位的一些属性以及我的军队中将有多少单位。

  2. 创建一个 armies 数组,我将在其中使用 createHumanoid

  3. 创建我的军队
  4. 我需要知道军队有多强大,所以我建立了 getArmyPower return namepower 的军队,这将在 4.2. .

  5. 中使用
  6. 战斗开始! (favoriteArmy = 'humans')

    4.1。正在创建 fight 方法并接受两个参数,第一个是 armies,第二个是 favoriteArmy

    4.2。使用 .map 方法,我将 getArmyPower 应用于我的每支军队(数组的元素)以了解他们的力量

    4.3。然后我使用 .sortarmy.power

    对它们进行降序排序

    4.4。 let victorious = armies[0]; 将为我获取排序数组中的第一个元素。拥有最高权力的人。或者您可以使用 destructuring 并将其写成 let [victorious] = armies; (表示数组中的第一个元素)

    4.5。我比较 victorious.namefavoriteArmy 来检查我感兴趣的军队是赢了还是输了。

/**
 * A function to create units
 */
const createHumanoid = (race, howMany, stats) => {

  return {
    name: race,
    armySize: howMany,
    unitStats: stats
  }

};

/**
 * Register the armies into battle
 */
let armies = [

  createHumanoid('humans', 12, {
    health: 10,
    attack: 12
  }),
  createHumanoid('zombies', 5, {
    health: 30,
    attack: 12
  }),

]

/**
 * Get the max power of each army - you can adjust the algorithm
 */
const getArmyPower = (army) => {
  return {
    name: army.name,
    power: +army.armySize * (+army.unitStats.health + +army.unitStats.attack)
  }

}

/**
 * Let them fight and see what your favorite army did in the battle
 */
function fight(armies, favoriteArmy) {

  armies = armies
    .map(army => getArmyPower(army))
    .sort((a, b) => b.power - a.power);

  let victorious = armies[0];

  if (victorious.name.toLowerCase() === favoriteArmy.toLowerCase()) {
    document.write('Live to see another day.');
  } else {
    document.write('The zombies are taking over!');
  }
}

fight(armies, 'humans');