随机图像函数Javascript



我正在尝试编写我的第一个自定义JavaScript函数,但遇到了一些障碍。

我正试图在我的网页上有三个缩略图,并让我的代码从许多图像中抓取三个图像,并在加载时显示它们。我遇到的问题围绕着图像的复制,或者当一个图像被选择两次时能够处理(这是类似的问题(。我试过很多不同的条件句,但似乎都无法突破。

这是我的代码:

let imgThumbnails = document.querySelectorAll('.img-fluid');
let chosenNums = [];
let imgNumber = () => { //object random
return Math.floor(Math.random() * (Object.keys(pictures).length));
}
const pictures = {
0 : { "src" : "Images - Copy/crack_plant.jpg", "alt" : "Seedling growing through bricks"},
1 : { "src" : "Images - Copy/desert_botanical.jpg", "alt" : "Phoenix's Desert Botanical Garden"},
2 : { "src" : "Images - Copy/LookUp.jpg", "alt" : "Looking up through forest"},
3 : { "src" : "Images - Copy/LookUpLeaves.jpg", "alt" : "Looking up at leaves"},
4 : { "src" : "Images - Copy/Road_Through_Trees.jpg", "alt" : "A path covered by trees"},
5 : { "src" : "Images - Copy/Sand.jpg", "alt" : "Tiny balls of sand formed by crabs"},
6 : { "src" : "Images - Copy/Snow.jpg", "alt" : "Powder day at Breckenridge"},
}; // these images are hosted locally for me at the moment
//attempt 1
const imgPopulate = () => {
imgThumbnails.forEach( a => {
let pictureNum = imgNumber();
while (!chosenNums.includes(pictureNum) && chosenNums.length <= 3) {
a.src = pictures[pictureNum].src;
chosenNums.push(pictureNum);
}
});
}
imgPopulate();

//attempt 2
while (chosenNums.length <= 3) {
let pictureNum = imgNumber();
if(chosenNums.includes() !== pictureNum) {
for(let i = 0; i <=3; i++) {
imgThumbnails[i].src = pictures[pictureNum].src
chosenNums.push(pictureNum);
}
} 
}
//attempt 3
do {
for(let i = 0; i <=3; i++) {
let pictureNum = imgNumber();
if(chosenNums.includes() !== pictureNum) {
imgThumbnails[i].src = pictures[pictureNum].src
chosenNums.push(pictureNum);
} else {
continue;
}
}
} while (chosenNums.length <= 3);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="views/css/bootstrap.min.css" rel="stylesheet">
<title>Showin Photos</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<img id = "photo1" class="img-fluid" src="" alt="">
</div>
<div class="col">
<img id = "photo2" class="img-fluid" src="" alt="">
</div>
<div class="col">
<img id = "photo3" class="img-fluid" src="" alt="">
</div>
</div>
</div>

<script src="views/js/bootstrap.min.js"></script>    
<script src="index.js"></script>
</body>
</html>

尝试:1:这个有时有效,除非它击中了已经使用过的图片对象中的一个数字。然后它只显示一个空白缩略图。我相信这个问题是因为它使用forEach。所以它每个项目只运行一次,即使它以前被使用过,而我的while循环不会影响它

2/3:我从这两次尝试中都遇到了同样的问题。这些尝试偶尔会将相同的图片用于不同的缩略图。我还得到一个:";Uncaught TypeError:无法设置未定义的"的属性"src";这与";pictures[pictureNum].src";,但是所有的缩略图仍然充满了图像?!?!

如果可以提供任何帮助,或者帮助修复这个代码,或者如果你有其他方法,我应该尝试写这个,这样我就可以尝试了。正如我所说,这是我第一次尝试自定义功能,我觉得我的视力很差,无法从不同的角度看待它。

谢谢!

您可以使用以下概念:

  1. 使用Object.values将图片转换为数组,并对数组进行混洗
// see shuffle options in the snippet
const data = shuffle(Object.values(pictures));
  1. 由于数据现在是混洗的,只需使用array.slice从数组中获取前3项即可
const selected = data.slice(0, 3);

如果你使用Flavios Copes排序来洗牌,你可以在一行中完成:

const selected = Object.values(pictures).sort(() => Math.random() - 0.5).slice(0, 3);

下面的代码段:

const pictures = {
0: {
"src": "Images - Copy/crack_plant.jpg",
"alt": "Seedling growing through bricks"
},
1: {
"src": "Images - Copy/desert_botanical.jpg",
"alt": "Phoenix's Desert Botanical Garden"
},
2: {
"src": "Images - Copy/LookUp.jpg",
"alt": "Looking up through forest"
},
3: {
"src": "Images - Copy/LookUpLeaves.jpg",
"alt": "Looking up at leaves"
},
4: {
"src": "Images - Copy/Road_Through_Trees.jpg",
"alt": "A path covered by trees"
},
5: {
"src": "Images - Copy/Sand.jpg",
"alt": "Tiny balls of sand formed by crabs"
},
6: {
"src": "Images - Copy/Snow.jpg",
"alt": "Powder day at Breckenridge"
},
};
// shuffle array using Durstenfeld shuffle algorithm 
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// convert to an array and shuffle
const data = shuffle(Object.values(pictures));
// grab the first 3
const selected = data.slice(0, 3);
console.info(selected);
// one liner using Flavios Copes sort 
console.info(Object.values(pictures).sort(() => Math.random() - 0.5).slice(0, 3));

好吧,首先,您不需要有数字键的对象。这本质上是一个数组。数组将比对象更简单地为您提供所需的功能。

您只需要while循环来检查它刚刚拾取的阵列中的随机图像是否已经是拾取的图像,您可以通过单独存储生成的随机图像来完成这一操作。

let pics = document.querySelectorAll(".img-fluid");
let chosenNums = [];
let getRandom = () => { 
return Math.floor(Math.random() * pictures.length);
}
// An object with sequential numbers for keys is essentially an array
// so just use an Array.
const pictures = [
{ "src" : "Images - Copy/crack_plant.jpg", "alt" : "Seedling growing through bricks"},
{ "src" : "Images - Copy/desert_botanical.jpg", "alt" : "Phoenix's Desert Botanical Garden"},
{ "src" : "Images - Copy/LookUp.jpg", "alt" : "Looking up through forest"},
{ "src" : "Images - Copy/LookUpLeaves.jpg", "alt" : "Looking up at leaves"},
{ "src" : "Images - Copy/Road_Through_Trees.jpg", "alt" : "A path covered by trees"},
{ "src" : "Images - Copy/Sand.jpg", "alt" : "Tiny balls of sand formed by crabs"},
{ "src" : "Images - Copy/Snow.jpg", "alt" : "Powder day at Breckenridge"}
]; 
// Keep looping until we have 3 randoms
while(chosenNums.length < 3){
let random = getRandom();  // Get a random
// Check to see if the random is NOT already in the output array
if(!chosenNums.includes(random)){
chosenNums.push(random); // It's not so add it
}
}
// Now that the output array has 3 randoms in it, loop over them
chosenNums.forEach(function(num, index){
// Set up the img element corresponding to the loop index
// with the data from the picture corresponding to the index
// in the array of randoms
pics[index].src = pictures[num].src;
pics[index].alt = pictures[num].alt;  
});
<div class="container">
<div class="row">
<div class="col">
<img id = "photo1" class="img-fluid">
</div>
<div class="col">
<img id = "photo2" class="img-fluid">
</div>
<div class="col">
<img id = "photo3" class="img-fluid">
</div>
</div>
</div>

最新更新