javascript - 我需要在此代码中添加什么来阻止随机生成的图像重复自己?
问题描述
您好,我试图找到解决此问题的方法并且正在苦苦挣扎。我对 Javascript 很陌生!此代码可在单击按钮时生成随机图像,但图像会随机重复。我想显示所有图像,但不重复已经显示的图像。我知道我应该添加一个 for 循环和 if 语句,但不知道如何编写它。这些只是数组中的几个示例图像,我实际上将在最后的东西中有 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");
window.onload = () => generateRandomPicture(imageArray);
button.addEventListener("click", () => generateRandomPicture(imageArray));
function generateRandomPicture(array){
let randomNum = Math.floor(Math.random() * array.length);
image.setAttribute("src", array[randomNum]);
}
解决方案
我认为这更像是你想要做的。(我的另一个答案允许重复循环遍历同一个列表并每次随机化它,但是对于宾果游戏,你不需要所有这些。)
该populateImgs
函数获取一个 url 列表并遍历页面上的所有 img 元素,将每个 src 属性设置为不同的 url,或者如果 url 太少而无法填充所有 img 则失败。当函数被调用时,urls
参数是从一个打乱的部分 url 列表中动态构建的。(生成的 url 比您的原始 url 短,其中包含许多我为简洁而省略的参数。)
该shuffle
函数使用相同的算法,但实现方式略有不同(使用看起来更简洁的while(--i > 0){ swap(array, i, randLessThan(i)); }
)。
window.addEventListener('DOMContentLoaded', function(){
// Defines an array of strings that identify photos
const photoIds = [
"1508185159346-bb1c5e93ebb4", "1495480393121-409eb65c7fbe",
"1501611724492-c09bebdba1ac", "1417106338293-88a3c25ea0be",
"1500520198921-6d4704f98092", "1504966981333-1ac8809be1ca"
];
// Calls `populateImgs`, w/ a list of randomized urls based on photoIds
populateImgs(
shuffle(photoIds).map(id => `https://images.unsplash.com/photo-${id}`)
);
function populateImgs(urls){
// Shows one photo in each img element
const imgs = document.querySelectorAll("img");
if(urls.length < imgs.length){ return console.log("Not enough photos"); }
let index = -1;
while (++index < imgs.length){
imgs[index].setAttribute("src", urls[index]);
};
}
function shuffle(array){
// Uses helper functions to randomize array, returns randomized array
const
randLessThan = (num) => Math.floor(Math.random() * num),
swap = (arr, i, rand) => { let temp=arr[rand]; arr[rand]=arr[i]; arr[i]=temp; };
// Iterates backwards, swaps each item with a random earlier item, ignores i==0
let i = array.length;
while(--i > 0){ swap(array, i, randLessThan(i)); }
return array;
}
});
img{ width: 100px; height: 80px; object-fit: cover; margin: 15px; }
<div class="row">
<img/><img/>
</div>
<div class="row">
<img/><img/>
</div>
推荐阅读
- ios - 使 UiTextField 只接受粘贴选项 - Swift
- android - 在 Android 中打开外部数据库时出现错误消息
- python - 为什么_thread 在远程服务器上不起作用?
- mongodb - MongoDb:更新集合字段的值以删除非数字字符
- sql - 使用 PL/SQL 匿名块插入
- c - 将联合地址类型转换为无符号 8 位 char* 可能是什么意思?
- laravel - Laravel Spatie 权限获取用户资源及其角色和权限
- mongodb - 我应该为大容量的高写入创建一个全新的实例吗?
- reactjs - 尝试导入错误:'default' 没有从 '../assertThisInitialized/_index.mjs' 导出 - webpack 错误地将命名导入导入为默认值
- python - 构建 URL 列表时 Scrapy 错误无效的 xPath 表达式