限制数组中的随机元素显示在图像标记中

时间:2016-08-02 05:47:49

标签: javascript jquery html arrays

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

问题:

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

含义:

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

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

但是,我正在考虑限制例如:C中的元素Array_A要显示5次,这意味着index = 2的随机数只有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>

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

3 个答案:

答案 0 :(得分:1)

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

逻辑

  1. 创建原始数组的副本,以便不覆盖原始数组。
  2. 获取随机数,并将其转换为int。为了确保它在范围内,您应该在虚拟阵列的长度上使用%
  3. 现在您的随机索引的范围正确,请在结果数组
  4. 中推送此元素
  5. 现在递减计数,如果存在的话。如果count等于0,则将其从虚拟数组中删除。这将确保在给定的时间后元素不会重复。
  6. 现在您有一个随机且唯一的图像名称列表。返回它然后循环它们并更新标签。

    示例

    &#13;
    &#13;
    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))
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

请阅读我的评论以了解逻辑。

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>

答案 2 :(得分:0)

可能你可以做类似下面的代码片段。每次鼠标点击容器div时,它将显示两个随机图像。图像具有由displayLimit指定的配额(当前全部设置为5)。您可以在Plunker上测试代码。

&#13;
&#13;
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);
&#13;
<!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>
&#13;
&#13;
&#13;