javascript - 获取子函数中父字段的名称
问题描述
我需要在子函数中获取父元素(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;
})
}
}
}
解决方案
您可以尝试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';
});
推荐阅读
- ios - 将 2 个 API 调用的结果与 RxSwift 结合起来,为相同的对象获取不同的属性
- amazon-web-services - 如何从 API 网关端点向 lambda 授权方提供自定义数据
- maven - 如何使用 maven-build-plugin 访问私有 swagger API?
- python - 在容器内发送按键
- r - nlme::lmList 和观星者?
- css - Angular 6 在项目中混合样式
- amp-html - 当无效的 amp 页面缓存在 google 缓存中并打开缓存 url 时会发生什么
- html - 错误在 mpdf 6.1 中未设置字体或默认字体
- firebase - 如何为连续的数据流提供连续的 Firebase 云功能?
- r - 计算 R 的 Date 和 POSIXct 不同的美学