有人可以建議如何解決這個問題嗎?我需要使用“i”在 JavaScript 回圈中顯示一個位置,但如果點數相同,我希望保持相同的位置。請查看簡化的螢屏截圖。

我嘗試了不同型別的回圈,但無法達到預期的效果。
uj5u.com熱心網友回復:
你幾乎已經回答了你的問題。只是在積分相同時不要計數i,同時遍歷您的積分。
沒有任何代碼示例,我只是假設您的點存盤在一個陣列中。
const points = [6, 4, 2, 2, 2, 1];
let i = 0;
points.forEach((point, index) => {
if (point !== points[index - 1]) {
i ;
}
console.log(i); // 1, 2, 3, 3, 3, 4
});
這應該是您的預期結果。
請注意,他不是解決問題的唯一方法,只是如何回圈和計數的眾多方法之一。你可以像我一樣使用常規的 for 回圈、forEach、while 或任何你想要的。
這是另一個可能很有趣的解決方案,使用 Array.reduce 創建一個新的位置陣列
const points = [6, 4, 2, 2, 2, 1];
const positions = points.reduce((acc, point, index) => {
if (point !== points[index - 1]) {
acc.push(acc[index - 1] 1 || 1);
} else {
acc.push(acc[index - 1]);
}
return acc;
}, []);
console.log(positions); // [1, 2, 3, 3, 3, 4]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530439.html
上一篇:雖然回圈不斷回到結束條件
