1 回答

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;
});
}
添加回答
舉報(bào)