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

如何修改Javascript代码以避免随机生成的图片出现重复?

实现不重复随机抽取图片的方案

你不需要写复杂的for循环判断,只要多维护一个「待抽取图片池」就可以实现需求:

  • 初始化的时候把所有图片都放入待抽取池
  • 每次点击从待抽取池里随机拿一张展示,同时把这张从池子里删掉
  • 待抽取池为空的时候,重新把所有图片放回池子里,就可以开始下一轮不重复抽取,非常适合你后续要放55张图的场景

修改后的完整代码如下:

const imageArray = [
    "https://images.unsplash.com/photo-1508185159346-bb1c5e93ebb4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=55cf14db6ed80a0410e229368963e9d8&auto=format&fit=crop&w=1900&q=80",
    "https://images.unsplash.com/photo-1495480393121-409eb65c7fbe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=05ea43dbe96aba57d48b792c93752068&auto=format&fit=crop&w=1351&q=80",
    "https://images.unsplash.com/photo-1501611724492-c09bebdba1ac?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ebdb0480ffed49bd075fd85c54dd3317&auto=format&fit=crop&w=1491&q=80",
    "https://images.unsplash.com/photo-1417106338293-88a3c25ea0be?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=d1565ecb73a2b38784db60c3b68ab3b8&auto=format&fit=crop&w=1352&q=80",
    "https://images.unsplash.com/photo-1500520198921-6d4704f98092?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ac4bc726064d0be43ba92476ccae1a75&auto=format&fit=crop&w=1225&q=80",
    "https://images.unsplash.com/photo-1504966981333-1ac8809be1ca?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=9a1325446cbf9b56f6ee549623a50696&auto=format&fit=crop&w=1350&q=80"
];

const image = document.querySelector("img");
const button = document.querySelector("button");

// 初始化待抽取图片池,深拷贝原始数组避免修改原数据
let remainingImages = [...imageArray];

window.onload = () => generateRandomPicture();
button.addEventListener("click", () => generateRandomPicture());

function generateRandomPicture(){
    // 待抽取池为空就重置,不需要轮询的话删掉这段逻辑加按钮禁用即可
    if(remainingImages.length === 0){
        remainingImages = [...imageArray];
    }
    // 从待抽取池随机取索引
    const randomIndex = Math.floor(Math.random() * remainingImages.length);
    // 取到对应的图片地址
    const selectedImage = remainingImages[randomIndex];
    // 展示图片
    image.setAttribute("src", selectedImage);
    // 把已经展示过的图片从待抽取池移除
    remainingImages.splice(randomIndex, 1);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:03