从对象的下一个索引中获取值



我正在循环遍历一个对象。循环运行得很好,但在value的编号变为zero之后,它将跳到下一个key

我希望在从每个key迭代之后,它应该转到下一个。

let trackOfReaction = {
heart: 5,
fire: 4,
clap: 0,
wow: 2,
like: 1,
}
setInterval(() => {
for (const [key, value] of Object.entries(trackOfReaction)) {
if (value !== 0) {
trackOfReaction[key] = value - 1
const userReaction = {
reaction: key,
storedReaction: true,
};
console.log(userReaction)
break;
}
}
}, 2000);

以下是的预期输出

预期输出

{
reaction: "heart",
storedReaction: true
},
{
reaction: "fire",
storedReaction: true
},
{
reaction: "wow",
storedReaction: true
},
{
reaction: "like",
storedReaction: true
},
{
reaction: "heart", // here after completing of the first set heart should print again
storedReaction: true
},
{
reaction: "fire",
storedReaction: true
},
{
reaction: "wow",
storedReaction: true
},
{
reaction: "heart",  // like became 0 so it not print, loop goes again back to heart
storedReaction: true
},...so on

这适用于

注意拼接,这样当值变为0 时,超时将不再需要更长时间

const trackOfReaction = {   heart: 5,   fire: 4,   clap: 0,   wow: 2,   like: 1, };
// filter the items so we do not even process "clap"
const arr = Object.entries(trackOfReaction).filter(([key, value]) => value > 0);
let cnt = 0;
let tId = setInterval(() => {
if (cnt >= arr.length) cnt = 0;
const [key, value] = arr[cnt];
if (value === 0) {
// no need to subtract
cnt++
return;
}
const userReaction = { reaction: key, storedReaction: true, value: value };
console.log(userReaction);
arr[cnt][1]--; // count down the entry
if (arr[cnt][1] === 0) arr.splice(cnt,1); // shorten the array
console.log(JSON.stringify(arr))
const cont = arr.reduce((acc, [key, value], i) => { acc += value; return acc; }, 0);
if (cont === 0) { // stop when the array is empty or all values are 0
clearInterval(tId);
console.log("stopped");
return; // stop
}
cnt++; // add one
}, 1000);

最新更新