代码之家  ›  专栏  ›  技术社区  ›  Federico

2个随机图像,但不是同一个

  •  0
  • Federico  · 技术社区  · 8 年前

    我有一个函数,显示从一个文件夹中选取的两个随机图像。有没有可能我可以修改代码,这样我就不会有两次相同的图像作为结果?

    事先谢谢。

    var theImages = new Array()
    
    theImages[0] = 'img/dyptichs/f-1.jpg'
    theImages[1] = 'img/dyptichs/f-2.jpg'
    theImages[2] = 'img/dyptichs/f-3.jpg'
    theImages[3] = 'img/dyptichs/f-4.jpg'
    theImages[4] = 'img/dyptichs/f-5.jpg'
    
    var j = 0
    var p = theImages.length;
    var preBuffer = new Array()
    for (i = 0; i < p; i++){
       preBuffer[i] = new Image()
       preBuffer[i].src = theImages[i]
    }
    var WI1 = Math.round(Math.random()*(p-1));
    var WI2 = Math.round(Math.random()*(p-2));
    
    function showImage1(){
    document.write('<img src="'+theImages[WI1]+'">');
    }
    function showImage2(){
    document.write('<img src="'+theImages[WI2]+'">');
    }
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   Terry Lennox    8 年前

    你可以这样做:

    var WI1 = Math.round(Math.random()*(p-1));
    var WI2 = Math.round(Math.random()*(p-1));
    while (WI2 === WI1) {
        WI2 = Math.round(Math.random()*(p-1));
    }
    

    我们不断生成一个新的数字,直到它与WI1不同,确保它是唯一的。

        2
  •  2
  •   James Long    8 年前

    我个人处理的方法是随机化数组,然后只获取前2个条目。这样你仍然随机选择2,但你保证不会得到相同的2。

    var theImages = new Array()
    
    theImages[0] = 'img/dyptichs/f-1.jpg'
    theImages[1] = 'img/dyptichs/f-2.jpg'
    theImages[2] = 'img/dyptichs/f-3.jpg'
    theImages[3] = 'img/dyptichs/f-4.jpg'
    theImages[4] = 'img/dyptichs/f-5.jpg'
    
    var randomImages = theImages
        .concat()
        .sort(function () {
    
            return Math.random() > 0.5
                ? 1
                : -1;
    
        })
        .slice(0, 2);
    
    function showImage1() {
        document.write('<img src="' + randomImages[0] + '">');
    }
    
    function showImage2() {
        document.write('<img src="' + randomImages[1] + '">');
    }
    

    编辑:包含完整解决方案的原始数组

        3
  •  1
  •   riv    8 年前
    var WI1 = Math.floor(Math.random()*p);
    var WI2 = Math.floor(Math.random()*(p-1));
    if (WI2 >= WI1) {
      WI2 += 1;
    }
    

    使用floor而不是round并减去1,因为使用round可以减少两倍获得第一个或最后一个元素的机会。

    在这种情况下,if技巧比循环稍好,尽管循环更容易应用于更复杂的情况。