【问题标题】:Same random images on same page (I want to show different random images)同一页面上的相同随机图像(我想显示不同的随机图像)
【发布时间】:2017-05-03 17:07:41
【问题描述】:

我是新来的,我的代码在那里,工作正常,但有时我在页面上看到相同的图像。我怎样才能显示它是不同的每张图片。

<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>

【问题讨论】:

  • theImagesotherImagesotherImages2 是否总是包含相同的图像?您是否正在尝试使显示在正文中的 3 个图像始终不同? preBuffer 数组的用途是什么?

标签: javascript random


【解决方案1】:

您需要确保每个随机选择的图像与其他图像不同。

您可以使用 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。

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多