【问题标题】:Limit randomized element from array to be displayed in image tag限制数组中的随机元素显示在图像标签中
【发布时间】:2016-08-03 19:55:30
【问题描述】:

我创建了一个随机图像数组,2 个随机生成的图像将显示在我的 HTML 正文中创建的 2 个图像标签中。每个随机图像只会显示一次。

问题:

但是,我现在面临一个障碍。我试图将数组中的单个元素随机限制为最多 n 次。

意思:

Array_A = [A, B, C, D, E]

我已经随机化了Array_A,随机生成的图像将显示在我的 HTML 正文中的两个<img> 中。因此,当我执行console.log 时,将显示来自Array_A 的两个元素。

但是,我正在考虑限制例如:Array_A 中的元素 C 显示 5 次,这意味着 index = 2 的随机计数仅为 5,如果计数超过 5,则随机再次调用方法以获取另一个随机元素。

我已经在网上搜索了任何参考资料,但没有找到任何参考资料。

var Brand_list = [];

 var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png", "lib/img/Brands/E.png"];

 //Randomised Brand Offer
 //Auto populate into brand container once randomised
 $('#BrandWinlist > img').each(function(i, img) {
   var flag = false;
   do {
     random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
     if (Brand_list.indexOf(random_BrandIndex) == -1) {
       flag = true;
       Brand_list.push(random_BrandIndex);
       console.log("random_BrandIndex:" + random_BrandIndex);
       var Brand = BrandNameArray[random_BrandIndex];
       $(img).attr('src', Brand).attr("alt", Brand).show();
     }
   } while (!flag);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="GameWinBrand_Container">
  <div id="BrandWinlist" class="GameWinBrand_innerScroll">
    <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
    <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
  </div>
</div>

因此,有什么方法可以限制随机元素显示指定的次数?

【问题讨论】:

  • “重新显示”图像时是否会刷新页面/重新加载文档? IE。这是需要用 cookie/localstorage 存储的东西吗?
  • @haxxxton,不,页面不会刷新/重新显示图像时重新加载文档,它必须显示下一个可用的随机图像。我认为需要跟踪计数。
  • 如果显示计数达到 5,则从数组 (images.splice(i,1)) 中删除该图像并继续正常的随机图像选择操作。
  • @Redu 你有例子吗?我会假设“i”是元素的名称?如果是这样,如何引用数组中元素的名称?
  • @Luke i 是要从图像数组中删除的图像元素的索引。一旦我有空,我将在今天晚些时候发布一个答案......但就目前而言,我可以说你可以在图像数组项中保留一个 displayCount 属性。每个项目都可以是一个对象来保存displayCountimage 属性。

标签: javascript jquery html arrays


【解决方案1】:

以下是从给定数组中获取随机元素的示例。

逻辑

  1. 创建原始数组的副本,以免覆盖原始数组。
  2. 获取随机数,并将其转换为 int。为确保其在范围内,您应该在虚拟数组的长度上使用 %
  3. 既然您有正确范围内的随机索引,请将此元素推送到结果数组中
  4. 现在减少计数,如果存在的话。如果计数等于0,则将其从虚拟数组中删除。这将确保元素在给定的时间后不会重复。

现在您有了一个随机且唯一的图像名称列表。返回它,然后循环它们并更新标签。

样本

var BrandNameArray = [{src: "lib/img/Brands/A.png", maxCount:2},
                      {src: "lib/img/Brands/B.png"},
                      {src: "lib/img/Brands/C.png", maxCount:1},
                      {src: "lib/img/Brands/D.png"},
                      {src: "lib/img/Brands/E.png"}];

function getRandomList(arr, len, maxRepeat) {
  // To store result
  var _r = []

  // To ensure original array is not updated
  var _a = arr.slice(0);

  for (var i = 0; i < len; i++) {
    // get random number and find index using % to ensure index is in range
    var _index = Math.floor(Math.random() * 10) % _a.length;
    _r.push(_a[_index].src);
    if (_a[_index].hasOwnProperty("maxCount") && --_a[_index].maxCount <=0) {
      // remove added element from temp array.
      _a.splice(_index, 1);
    }
  }
  return _r
}

console.log(getRandomList(BrandNameArray, 8))
console.log(getRandomList(BrandNameArray, 5))

【讨论】:

  • 我认为您没有收到我的问题。您提供的解决方案只是从元素数组中获取唯一项目。我已经成功地做到了这一点。但是,我面临的问题是:我想将“lib/img/Brands/A.png”限制为能够随机化并仅显示 5 次,在第 5 次之后,“A.png”将不会随机再次展出。还是我不理解你?
  • 你如何确定一个特定的元素,例如:元素“D.png”是在随机化后显示的元素计数 5 次后要删除的索引?
  • 我想我还没有完全理解你的问题。所以这就是我的理解。您有一组图像,它们将以随机顺序显示。现在每个图像都可以重复x 次。在此之后它不应该出现,但其他图像可以随机出现。这是你要找的吗?
  • 我有一组图像。数组中的图像可以随机化并无限期显示,除了数组中的一张图像,只能随机化并显示x次。之后,它不应该随机出现,但其他图像仍然可以随机出现
  • @Luke 我已经更新了答案。注意我有空来更新你的数组。希望这是一个可行的选择。
【解决方案2】:

请阅读我的 cmets 以了解逻辑。

var Brand_list = [];

 var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png", "lib/img/Brands/E.png"];

 var limit = 2;  //this is where you will set limit of the image to appear randomly
 var limitImageAtIndex = 0; //here you define Index of image that has to be limited, i have set to zero it means first image is limited to be appear 2 times

 setTimeout(randomize,1000);

 function randomize(){
   //Randomized Brand Offer
 //Auto populate into brand container once randomized
 $('#BrandWinlist > img').each(function(i, img) {
   var flag = false;
   do {
     random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);

       //here is the logic to limit the image
       //if (Brand_list.indexOf(random_BrandIndex) == -1) {

       if(limitImageAtIndex == random_BrandIndex){
          limit--; 
          if(limit<0){
               continue; //continue to next iteration skip this image
          }
       }
       ///////////////
  
       flag = true;
       Brand_list.push(random_BrandIndex);
       console.log("random_BrandIndex:" + random_BrandIndex);
       var Brand = BrandNameArray[random_BrandIndex];
       $(img).attr('src', Brand).attr("alt", Brand).show();
     //}
   } while (!flag);
  });
  setTimeout(randomize,2000);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="GameWinBrand_Container">
  <div id="BrandWinlist" class="GameWinBrand_innerScroll">
    <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
    <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
  </div>
</div>

【讨论】:

  • 我仍然能够返回超过为数组中索引设置的限制的值
  • 自动化这些图像的代码在哪里(如 setTimeOut 函数)
  • @Luke 你在吗?
  • 嘿@Luke,再次尝试我的代码点击运行代码 sn-p 并自己查看输出,如果需要解释,请告诉我。
  • 好吧,当我运行你的代码时,图像索引“0”显示了两次以上。我想我确实理解你的解决方案
【解决方案3】:

也许您可以执行以下 sn-p 之类的操作。每次鼠标单击容器 div 时,它将显示两个随机图像。图像具有由displayLimit 指定的配额(当前全部设置为 5)。您可以在Plunker 测试代码。

function selectBrand(e){
  var newImages;
  if (images.length < 6) {
  for (var oldImage of oldImages) { oldImage.displayCount < oldImage.displayLimit && images.push(oldImage)};
    oldImages = [];
  }
  newImages = images.length >= 2 ? Array(2).fill()
                                           .map(e => {var image = images.splice(~~(Math.random()*images.length),1)[0];
                                                      image.displayCount++;
                                                      return image})
                                 : imagesOnDisplay;
  newImages.forEach((image,i) => imageElements[i].src = image.src);
  oldImages = imagesOnDisplay.slice();
  imagesOnDisplay = newImages.slice();
}

var BrandNameArray = ["http://www.sonus-festival.com/e276/e975/e564/photo1773/250-MG_0222_eng.jpg",
                      "http://www.sonus-festival.com/e276/e975/e564/photo1790/250-KIDKUTSMEDIA-4524_eng.jpg",
                      "http://mlampros.github.io/images/11st.jpeg",
                      "http://oneeyeland.com/awards/images/thumb/2015/194652.jpg",
                      "http://oneeyeland.com/awards/images/thumb/2015/195491.jpg",
                      "http://oneeyeland.com/awards/images/thumb/2015/195821.jpg",
                      "http://oneeyeland.com/awards/images/thumb/2015/197506.jpg",
                      "http://oneeyeland.com/250/218410-one-eyeland-fenna-2-by-gemmy-woud-binnendijk.jpg"],
            limits = [5,5,5,5,5,5,5,5],
            images = BrandNameArray.map((e,i) => ({         src: e,
                                                   displayCount: 0,
                                                   displayLimit: limits[i]
                                                 })),
         oldImages = [],
   imagesOnDisplay = Array(2).fill().map(e => images.splice(~~(Math.random()*images.length),1)[0]),
         imagesDiv = document.getElementById("BrandWinlist"),
     imageElements = imagesDiv.querySelectorAll("img");
     
imagesOnDisplay.forEach((image,i) => imageElements[i].src = image.src);
imagesDiv.addEventListener("click", selectBrand);
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js" async></script>
</head>

<body>
  <div class="GameWinBrand_Container">
    <div id="BrandWinlist" class="GameWinBrand_innerScroll">
      <img id="GameBrand_1" style="width:250px; height:250px; top:0px; left:0px; border:0px; outline:0px">
      <img id="GameBrand_2" style="width:250px; height:250px; top:0px; left:330px; border:0px;">
    </div>
  </div>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2023-03-07
    • 2013-12-24
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多