首页 > 解决方案 > 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]+'">');
}

标签: javascript

解决方案


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.


推荐阅读