<body>
<div><% for(var i=0;i<pictures.length;i++){ %>
<img src="images\<%= Math.floor((Math.random() * pictures.length) + 1) %>.jpg">
<%}%>
</div>
这里,Math.random正在执行3个随机图像,但不是唯一的。如何生成唯一编号以使图像执行唯一?
答案 0 :(得分:1)
因此,如果没有数组存储您的随机数,这是不可能的(如果我没有误解这个问题)。所以基本上你正在做的是创建一个数组并存储生成的随机数。然后,如果数字是唯一的&#39;将它们添加到数组中。然后循环遍历数组构造图像标记的源字符串,然后只使用构造的源调用图像标记。
<% var arr = [] %>
//<!-- Make the while loop the size you eg. how many images you want shown.
// Here it is the length of the amount of pictures change it to suit your needs -->
<% while(arr.length < pictures.length ){
//<!-- Create your random number -->
var randomNum = Math.floor((Math.random() * pictures.length) + 1);
//<!-- If the random number is not in the array -->
if(arr.indexOf(randomNum) == -1){
// Add the random number to the array
arr.push(randomNum);
}
} %>
<!-- Loop through the array -->
<%arr.forEach(function(number){ %>
<!-- Construct image source -->
<% var source = "images/"+number+".jpg"; %>
<!-- Create the image using the constructed source -->
<img src=<%=source%>>
<%});%>