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

javascript - 在子函数中获取父字段的名称-LMLPHP

 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;
        })
      }
    }
  }

最佳答案

您可以尝试在该对象的主体外部定义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';
});

关于javascript - 在子函数中获取父字段的名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59763513/

10-12 15:39