You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现随机步长递增的for循环,为location分配随机数量的boulder数据

随机步长循环分配boulder数据到location的问题解决

核心需求

  • 给每条location数据分配随机数量的boulder数据
  • 需要实现按随机步长递增的for循环:初始索引为0,生成随机步长后索引叠加该步长进入下一轮迭代,例如首次生成随机数5则下一个索引为0+5,第二次生成随机数3则第三个索引为5+3,以此类推

现有代码片段

随机数生成函数

const randomNum = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min) + min)
}

报错的原实现代码

const allBoulders = async() => {await Boulder.find().exec()}

for (i=0, i < allBoulders.length; i+=upperCount;) {
    console.log(i)
    const area = location.area;
    const place = location.place;
    const latitude = location.latitude;
    const longitude = location.longitude;
    const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude});
    const upperCount = indexCount + randomNum(1, 5)
    const boulderSet = allBoulders.slice(indexCount, upperCount);
    boulderLocation.boulders.push(...boulderSet);
    // await boulderLocation.save()
    console.log(boulderLocation)
    indexCount = upperCount;
};

报错信息

for (i=0, i < allBoulders.length; i+=upperCount;) {
                                     ^

ReferenceError: upperCount is not defined

已验证解决方案

修复后可运行代码

locations.forEach(async(location) => {
    const allBoulders =  await Boulder.find().exec()
    // console.log(foundAllBoulders);
    for (let i = 0; i < allBoulders.length;) {
        const area = location.area;
        const place = location.place;
        const latitude = location.latitude;
        const longitude = location.longitude;
        const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude});
        const random = randomNum(1, 5);
        const upperCount = i + random;
        const boulderSet = allBoulders.slice(i, upperCount);
        boulderLocation.boulders.push(...boulderSet);
        // await boulderLocation.save()
        console.log(boulderLocation);
        i += random;
    }
})

解决思路

原报错核心原因是upperCount变量在for循环的迭代器位置被调用时还未完成声明,同时原代码还存在异步函数调用错误、索引变量混用的问题。修复方案采用forEach遍历所有location数据,内部嵌套for循环,在循环体内优先生成随机步长,使用同一个随机值计算切片上限和索引增量,彻底避免变量提前引用问题。

内容的提问来源于stack exchange,提问作者shoski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:15:03