对于 Y 循环计数器中的 X
For X of Y loop counters
我有这个standings
数组
{ pos: 1, competitor_id: 583, rating: 2049, tier: 1 },
{ pos: 2, competitor_id: 862, rating: 1818, tier: 1 },
{ pos: 3, competitor_id: 67, rating: 1762, tier: 1 },
{ pos: 4, competitor_id: 758, rating: 1750, tier: 1 },
{ pos: 5, competitor_id: 713, rating: 1735, tier: 1 },
{ pos: 6, competitor_id: 868, rating: 1730, tier: 1 },
{ pos: 7, competitor_id: 946, rating: 1706, tier: 2 },
{ pos: 8, competitor_id: 893, rating: 1705, tier: 2 },
{ pos: 9, competitor_id: 731, rating: 1695, tier: 2 },
{ pos: 10, competitor_id: 869, rating: 1692, tier: 2 },
{ pos: 11, competitor_id: 998, rating: 1672, tier: 2 },
{ pos: 12, competitor_id: 968, rating: 1661, tier: 2 },
{ pos: 13, competitor_id: 460, rating: 1656, tier: 2 },
{ pos: 14, competitor_id: 879, rating: 1648, tier: 2 },
{ pos: 15, competitor_id: 969, rating: 1631, tier: 2 },
{ pos: 16, competitor_id: 925, rating: 1629, tier: 2 },
{ pos: 17, competitor_id: 999, rating: 1626, tier: 2 },
{ pos: 18, competitor_id: 991, rating: 1619, tier: 2 },
{ pos: 19, competitor_id: 956, rating: 1618, tier: 2 },
{ pos: 20, competitor_id: 711, rating: 1617, tier: 2 },
{ pos: 21, competitor_id: 964, rating: 1616, tier: 2 },
我想在每次向下移动 6 行时将 tier
递增 1。
正如您在上面看到的那样,它可以正确切换到第 2 层,但无法在 pos:13 增加到 3,在 pos:19
我试过了
const tiersize = 6;
// setting the counters
let tiercounter = 1;
let limit = tiersize;
// running the loop
for (const row of standings) {
await connectionPromise
.query({
sql: 'update table set tier = ? where competitor_id = ?'
}, [tiercounter, row.competitor_id], );
if (row.pos == limit) {
tiercounter += 1;
limit += tiersize;
}
}
我做错了什么?
您正在检查 row.pos 数量的限制以及您每次更新的限制。这对条件没有意义。更新 if 条件如下。
for (const row of standings) {
await connectionPromise
.query({
sql: 'update table set tier = ? where competitor_id = ?'
}, [tiercounter, row.competitor_id], );
if (row.pos % tiersize == 0) {
tiercounter += 1;
limit += tiersize;
}
}
您正在更新数据库,但还没有更新数组。将 row.tier = tiercounter;
添加到循环中。
const tiersize = 6;
// setting the counters
let tiercounter = 1;
let limit = tiersize;
// running the loop
for (const row of standings) {
await connectionPromise
.query({
sql: 'update table set tier = ? where competitor_id = ?'
}, [tiercounter, row.competitor_id], );
row.tier = tiercounter;
if (row.pos == limit) {
tiercounter += 1;
limit += tiersize;
}
}
但是,您可以根据 pos
.
tiercounter
tiercounter = Math.floor((row.pos-1) / tiersize) + 1;
更新后的代码将是:
const tiersize = 6;
// running the loop
for (const row of standings) {
let tiercounter = Math.floor((row.pos - 1) / tiersize) + 1;
await connectionPromise
.query({
sql: 'update table set tier = ? where competitor_id = ?'
}, [tiercounter, row.competitor_id], );
row.tier = tiercounter;
}