我是新来的,我的代码在那里,工作正常,但有时我在页面上看到相同的图像。我怎样才能证明它与每一幅图像都不同。
<html>
<head>
<SCRIPT language=JavaScript>
var theImages = new Array()
theImages[0] = 'cow.png'
theImages[1] = 'donkey.png'
theImages[2] = 'monkey.png'
var otherImages = new Array()
otherImages[0] = 'cow.png'
otherImages[1] = 'donkey.png'
otherImages[2] = 'monkey.png'
var otherImages2 = new Array()
otherImages2[0] = 'cow.png'
otherImages2[1] = 'donkey.png'
otherImages2[2] = 'monkey.png'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
var preBuffer2 = new Array()
var preBuffer3 = new Array()
var preBuffer4 = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
preBuffer2[i] = new Image()
preBuffer2[i].src = otherImages[i]
preBuffer3[i] = new Image()
preBuffer3[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
var otherImage = Math.round(Math.random()*(p-1));
var otherImage2 = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}
function showImage2(){
document.write('<img src="'+otherImages[otherImage]+'">');
}
function showImage3(){
document.write('<img src="'+otherImages2[otherImage2]+'">');
}
</SCRIPT>
</head>
<body>
<SCRIPT language=JavaScript>
showImage();
</SCRIPT>
<SCRIPT language=JavaScript>
showImage2();
</SCRIPT>
<SCRIPT language=JavaScript>
showImage3();
</SCRIPT>
</body>
</html>
答案 0 :(得分:0)
您需要确保每个随机选择的图像与其他图像不同。
您可以使用while循环重复随机化,直到所选图像索引与其他图像索引不匹配为止:
var whichImage;
var otherImage;
var otherImage2;
whichImage = Math.round(Math.random()*(p-1));
while (otherImage == whichImage) {
otherImage = Math.round(Math.random()*(p-1));
}
while (otherImage2 == whichImage || otherImage2 == otherImage) {
otherImage2 = Math.round(Math.random()*(p-1));
}
如果您的阵列可能会改变大小,请小心,因为您可能会陷入循环。例如,如果一个数组的大小仅为1。