为了账号安全,请及时绑定邮箱和手机立即绑定

来自推送的 Foreach 数组返回空对象

来自推送的 Foreach 数组返回空对象

萧十郎 2023-07-20 15:37:57
我有一个数组,其中的对象是从函数内部的推送生成的,当我尝试直接查看数组中的对象时,我成功了,但我使用 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 中的对象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 } }
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

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


如果您尝试在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;

  });

}


查看完整回答
反对 回复 2023-07-20
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信