首页 > 解决方案 > 在显示当前图像时从阵列内的剩余图像中随机选择

问题描述

我需要创建一个显示图像的网页,该图像将在 2 秒内替换为另一张图像。阵列内共有 3 张图像。但是,当显示当前图像时,我的随机函数应该只允许从数组内的剩余图像中选择并在 2 秒后替换当前图像。

我能够随机化整个阵列内的图像,但无法从剩余的图像中随机化。在这方面需要帮助。谢谢。

$(function(){
	//prepare Your data array with img urls
	var dataArray=new Array();
	dataArray[0]="cat2.jpg";
	dataArray[1]="cat3.jpg";
	dataArray[2]="cat1.jpg";

	//start with id=0 after 2 seconds
	var thisId=0;

	window.setInterval(function(){
	var randomNum = Math.floor(Math.random() * dataArray.length);
	document.getElementById("thisImg").src = dataArray[randomNum];
	},2000); 
});
<!DOCTYPE html>
<html>
<head>
	<title>Task 2</title>
	
	<!-- calling external js file -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<img id="thisImg" alt="img" src="cat1.jpg"/>
	<script src ="Task2.js"></script>
</body>
</html>

标签: javascriptjqueryhtml

解决方案


尝试这种方法,只需在选择下一个图像之前过滤您的图像并随机选择。

const numbers = [1,2,3,4,5]
let currentNumber = 1;

const run = (numbers, cn) => {
  setInterval(() => {
    const filtered = numbers.filter(num => num !== cn);
    const random = filtered[Math.floor(Math.random() * filtered.length)]
    // here set background to random
    console.log(`
      Current: ${cn}
      Filtered: ${filtered}
      Next: ${random}
    `)
    cn = random;
  }, 3000)
}

run(numbers, currentNumber)


推荐阅读