推送中的Foreach数组返回空对象



我有一个数组,其中的对象是从函数内部的推送生成的,当我尝试直接查看数组中的对象时,我成功了,但我使用forEach来添加id使用服务的次数,但结果总是返回空。

client.onMessage(async message => {
count_commands.push({id:parseInt(regNumberPhone), age: 1});
});

const count_commands = [],
hash = Object.create(null),
result = [];
count_commands.forEach(function (o) {
if (!hash[o.id]) {
hash[o.id] = { id: o.id, age: 0 };
result.push(hash[o.id]);
}
hash[o.id].age += +o.age;
});

在count_commands 中查找de对象

console.log(count_commands);
Return:
[ { id: 559892099500, age: 1 },
{ id: 559892099500, age: 1 },
{ id: 559892099500, age: 1 } ]

但是要查看每个id的总和,数组返回空

console.log(result);
Return:
{}

我需要返回类似:

[ { id: 559892099500, age: 3 } }

您的代码正在按预期工作。即for循环将返回您需要的结构。我猜测的问题是,您正在注册一个事件处理程序,该事件处理程序将仅在收到onMessage事件后填充count_commands数组。

如果您试图在填充count_commands数组之前对其进行迭代,则会得到一个空结果。我怀疑如果console.log返回{}而不是[],还会有其他问题。

您需要将代码修改为类似于以下的内容

const count_commands = [];
const result = [];
const hash = {};
client.onMessage(async message => {
count_commands.push({id:parseInt(regNumberPhone), age: 1});
updateResults();
});
function updateResults() {
count_commands.forEach(function (o) {
if (!hash[o.id]) {
hash[o.id] = { id: o.id, age: 0 };
result.push(hash[o.id]);
}
hash[o.id].age += +o.age;
});
}

最新更新