首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将对象从函数工厂推入数组

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

Stack Overflow用户
提问于 2018-10-08 14:30:32
回答 1查看 262关注 0票数 0

我造了两个功能工厂,一个是僵尸工厂,一个是人类工厂。我想要一个函数,它能区分僵尸健康和人类攻击之间的区别。它适用于每个人一人,但我无法思考如何做多个人和僵尸。我试着把人类的物体推到一个数组中,这样我就可以把所有的攻击加起来(我会重复一遍僵尸),但是没有运气.

代码语言:javascript
复制
//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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-08 15:19:09

尝试类似于我的片段,您真正需要的是创建单元的方法。我使用了普通对象,但是如果您想返回casualties --比方说,您需要返回每个主对象的humanoids数组,并根据传入的伤害在战斗中对它们进行splice处理。放松点,你会看到你的军队战斗的!

--我追求的逻辑:

  1. 我需要一支军队! 1.1。要创建一支军队,首先我需要一些单位,所以我构建了createHumanoid (应该将它重命名为createArmy) 1.2。createHumanoid将帮助为部队设置一些财产,其中有多少将在我的军队中。
  2. 创建一个armies数组,在其中我将使用createHumanoid创建军队
  3. 我需要知道军队有多强大,所以我构建了返回军队的getArmyPowerpower,这将在4.2.中使用。
  4. 战斗开始了!(favoriteArmy = 'humans') 4.1。正在创建fight方法,并接受两个参数,一是armies,二是favoriteArmy。 4.2。使用.map方法,我将getArmyPower应用于我的每个军队(数组中的元素),以了解它们的威力。 4.3。然后我使用.sort将它们按army.power降序排序。 4.4。let victorious = armies[0];将从排序数组中获得第一个元素。拥有最高权力的人。或者您可以使用毁伤并像let [victorious] = armies;那样编写它(表示数组中的第一个元素) 4.5。我把victorious.namefavoriteArmy比较一下,看看我感兴趣的军队是赢了还是输了。

代码语言:javascript
复制
/**
 * 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');

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52704528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档