首页 > 解决方案 > 获取子函数中父字段的名称

问题描述

我需要在子函数中获取父元素(CentralS)的名称,该怎么做呢?..................................................... ..................................................... ..................................................... ..................................................... ..................................................... .....................................

在此处输入图像描述

 const roles = {
 CentralS: {
      'harvester': {
        'quantity': 3,
        'currentQuantity': _.sum(Game.creeps, (c) => {

          if (c.memory.role === 'harvester') {
            // console.log(c.memory.spawnName)
            console.log(Object.keys(this))
            console.log(this)

          }
          return c.memory.role === 'harvester';
        }),
        'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
      }
    },
    CentralS1: {
      'harvester': {
        'quantity': 3,
        'currentQuantity': _.sum(Game.creeps, (c) => {

          if (c.memory.role === 'harvester') {
            // console.log(c.memory.spawnName)
            console.log(Object.keys(this))
            console.log(this)

          }
          return c.memory.role === 'harvester';
        }),
        'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
      }
    },
    CentralS2: {
      'harvester': {
        'quantity': 3,
        'currentQuantity': _.sum(Game.creeps, (c) => {

          if (c.memory.role === 'harvester') {
            // console.log(c.memory.spawnName)
            console.log(Object.keys(this))
            console.log(this)

          }
          return c.memory.role === 'harvester';
        }),
        'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
      }
    }
  }

我的解决方案

const roles = {
    CentralS: {
      'harvester': {
        'quantity': 3,
        'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
      }
   }
}
for (const spawnName in roles) {
    for (const roleName in roles[spawnName]) {
      if (roles[spawnName].hasOwnProperty(roleName)) {
        roles[spawnName][roleName].currentQuantity = _.sum(Game.creeps, (c) => {
console.log(spawnName) // CentralS
          return c.memory.role === roleName && c.memory.spawnName === spawnName;
        })
      }
    }
  }

标签: javascript

解决方案


您可以尝试currentQuantity在该对象的主体之外定义属性,如下所示:

const roles = {
 CentralS: {
    'harvester': {
      'quantity': 3,
      'strength': [WORK, CARRY, CARRY, MOVE, MOVE]
    }
  }
};

roles.CentralS.harvester.currentQuantity = _.sum(Game.creeps, (c) => {
  if (c.memory.role === 'harvester') {
    // console.log(c.memory.spawnName)
    console.log(Object.keys(this))
    console.log(this)

    console.log(roles.CentralS);    
  }
  return c.memory.role === 'harvester';
});

推荐阅读