来自推送的 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 中的对象


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


萧十郎
浏览 83回答 1
1回答

月关宝盒

您的代码正在按预期工作。即 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;  });}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript