蕭十郎
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;
});
}
添加回答
舉報
0/150
提交
取消