<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var images1 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
var images2 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
var images3 = new Array("strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg");
var length = images1.length;
var randImg = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images1[randImg] + '" >');
var length = images2.length;
var randImg = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images2[randImg] + '" >');
var length = images3.length;
var randImg = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images3[randImg] + '" >');
</script>
</body>
</html>
我想比较阵列的图像,如果3张图像是草莓我想创建一个警告信息,比如'恭喜你赢了'但是我不能那样做,我怎么能这样做?
答案 0 :(得分:0)
试试这个:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var images = ["strawberry.jpg", "apple.jpg", "cherry.jpg", "orange.jpg", "pear.jpg"];
var length = images.length;
var randImg1 = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images[randImg1] + '" >');
var randImg2 = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images[randImg2] + '" >');
var randImg3 = Math.round(Math.random() * (length - 1));
document.write('<img src="' + images[randImg3] + '" >');
if (randImg1 == randImg2 && randImg2 == randImg3 && randImg3 == "strawberry.jpg") {
// You won!
}
</script>
</body>
</html>
请注意我删除了多余的images1
,2
和3
并将其替换为单个数组images
。我还删除了构造函数,并对length1
,2
和3
执行了相同的操作。
然而,关键部分是我如何定义3个随机变量,randImg1
,2
和3
。然后你可以稍后比较它们。