javascript - 在显示当前图像时从阵列内的剩余图像中随机选择
问题描述
我需要创建一个显示图像的网页,该图像将在 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>
解决方案
尝试这种方法,只需在选择下一个图像之前过滤您的图像并随机选择。
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)
推荐阅读
- php - 将ajax中的变量从一个页面传递到另一个页面
- reactjs - 为什么在我输入 TextField ReactJS 时会触发按钮的 onClick 事件
- c - 面临寻找大数立方体的问题
- apache-kafka - 如何为 Kafka 中的集群配置 server.properties
- java - 如何从集合中的excel数据中找到一些字符串元素?.contains 方法在我的情况下不起作用
- javascript - 如何使用不同的表 id 显示两个 html 表?
- python - PyInstaller Orange3 __main__ Python 脚本调用不同文件夹中的脚本不起作用
- java - 保存后休眠插入
- javascript - 页面显示纯 html 文本而不是呈现 html 表
- java - Java对工厂方法的DAO定义