亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

來自推送的 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 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號