第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

來(lái)自推送的 Foreach 數(shù)組返回空對(duì)象

來(lái)自推送的 Foreach 數(shù)組返回空對(duì)象

蕭十郎 2023-07-20 15:37:57
我有一個(gè)數(shù)組,其中的對(duì)象是從函數(shù)內(nèi)部的推送生成的,當(dāng)我嘗試直接查看數(shù)組中的對(duì)象時(shí),我成功了,但我使用 forEach 來(lái)添加 id 使用服務(wù)的次數(shù),但結(jié)果總是返回空。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 中的對(duì)象console.log(count_commands);Return:[ { id: 559892099500, age: 1 },  { id: 559892099500, age: 1 },  { id: 559892099500, age: 1 } ]但要查看每個(gè) id 的總和,數(shù)組返回空console.log(result);Return:    {}我需要像這樣返回:[ { id: 559892099500, age: 3 } }
查看完整描述

1 回答

?
月關(guān)寶盒

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊

您的代碼正在按預(yù)期工作。即 for 循環(huán)將返回您需要的結(jié)構(gòu)。我猜測(cè)的問題是您正在注冊(cè)一個(gè)事件處理程序,該處理程序count_commands僅在onMessage收到事件后才會(huì)填充數(shù)組。


如果您嘗試在count_commands填充數(shù)組之前迭代該數(shù)組,您將得到一個(gè)空結(jié)果。console.log我懷疑如果返回{}而不是返回還會(huì)存在其他問題[]。


您需要將代碼修改為類似于以下內(nèi)容


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;

  });

}


查看完整回答
反對(duì) 回復(fù) 2023-07-20
  • 1 回答
  • 0 關(guān)注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)