【问题标题】:2 random images but not the same one2张随机图片,但不是同一张
【发布时间】:2018-07-02 21:57:33
【问题描述】:

我有这个功能,可以显示从文件夹中挑选的两个随机图像。有没有机会我可以修改代码,这样我就不会两次获得相同的图像?

提前致谢。

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]+'">');
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你可以这样做:

    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 个条目。这样你仍然会随机选择 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] + '">');
      }
      

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

      【讨论】:

      • 你会把数组放在哪里?
      • @Federico 抱歉,我不明白这个问题。 randomImages 是数组,它在当前范围内(对我来说看起来像是全局范围)。这能回答你的问题吗?
      • 是的,但是图像在一个文件夹中,这里没有指定?
      • 使用随机比较器排序不是打乱序列的正确方法,因为它不会给出一致的随机结果。
      • @riv 你是绝对正确的。我想要一个简单的解决方案来快速解释,但是周围有更好的洗牌解决方案。例如在这个答案stackoverflow.com/a/2450976/557019
      【解决方案3】:
      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 技巧比循环稍好,尽管循环更容易应用于更复杂的情况。

      【讨论】:

      • WI1 为 4 时索引超出范围
      • 不可能是4,因为随机不可能是1。
      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 2016-09-07
      • 1970-01-01
      • 2016-06-15
      • 2022-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      相关资源
      最近更新 更多