javascript - 2 random images but not the same one
问题描述
I have this function that shows two random images picked from a folder. Is there any chance I can modify the code so that I won't have the same image twice as result?
Thanks in advance.
var theImages = new Array()
theImages[0] = 'img/dyptichs/f-1.jpg'
theImages[1] = 'img/dyptichs/f-2.jpg'
theImages[2] = 'img/dyptichs/f-3.jpg'
theImages[3] = 'img/dyptichs/f-4.jpg'
theImages[4] = 'img/dyptichs/f-5.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-2));
function showImage1(){
document.write('<img src="'+theImages[WI1]+'">');
}
function showImage2(){
document.write('<img src="'+theImages[WI2]+'">');
}
解决方案
You can do something like this:
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-1));
while (WI2 === WI1) {
WI2 = Math.round(Math.random()*(p-1));
}
We keep generating a new number until it's different from WI1, ensuring it is unique.
推荐阅读
- python - 如何让预提交只检查您更改的python代码,而不是整个文件
- javascript - 开玩笑的错误,不是 promise 的函数
- javascript - 如何在 Angular 8 中检测文件的字符集?
- node.js - 温斯顿自定义传输格式的消息
- python - Python字符串到类名
- mysql - 具有大型数据集的 Laravel API 加载速度非常慢
- python - Samco API 字典问题
- javascript - 如何在 MVC.Core 中显示漂亮的彩色和可折叠的 json
- python - Juptyter Notebook 中 matplotlib 的输出
- r - R中基于字符串过滤的聚合数据帧