如何指定这个随机图像脚本

How to specify this random image script

本文关键字:图像 脚本 随机 何指定      更新时间:2023-09-26

我有这个javascript显示一个随机图像点击:

function pickimg(){
var imagenumber = 4 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "images/1.png"
images[2] = "images/2.png"
images[3] = "images/3.png"
images[4] = "images/4.png"
var image = images[rand1]
document.randimg.src = image

是否有一种方法可以确保相同的图像不会连续出现两次?

这个小算法怎么样:

  1. 将最后使用的图像存储在数组
  2. 的槽0中
  3. 随机选取索引大于0的图像。
  4. 显示
  5. 用槽位0
  6. 中的图像替换
Javascript:

 images = new Array();
 images[0] = "images/1.png" //will be that last used image
 images[1] = "images/2.png"
 images[2] = "images/3.png"
 images[3] = "images/4.png"
 function pickimg(){
     var randomnumber = Math.random();
     // pick a random number from 1 to LENGTH (3)
     var rand1 = Math.round( (images.length-1) * randomnumber)+1;
     var image = images[rand1]; //get the image
    // switch so that the random image will be in the used
    // images slot (slot 0)
    images[rand1] = images[0] 
    images[0] = image 
    document.randimg.src = image
}