javascript - 尝试防止 DIV 中出现重复的随机项

标签 javascript jquery arrays

有人可以帮我解决这个问题吗?我需要做的就是防止重复显示。我正在填充一个数组并随机生成食谱。当您刷新页面时,有时同一项目会出现两次。我需要阻止这种情况发生。我在底部添加了一个 fiddle ,谢谢。

下面是我的代码:

 var recipe_data = [
   {
      "id":"11",
      "recipeName":"Hummus",
      "recipeCategory":"4",
      "recipeImageCategoryURL":"http://www.slurrpy.com/wp-content/uploads/2012/08/roasted-eggplant-hummus-800x500.jpg"
   },
   {
      "id":"12",
      "recipeName":"Antipasto",
      "recipeCategory":"4",
      "recipeImageCategoryURL":"http://static.menutabapp.com/img/cache/800x500/2012/10/23/7857b394d50293d29443dc09eac76b3d.jpeg"
   },
   {
      "id":"10",
      "recipeName":"Zucchini",
      "recipeCategory":"4",
      "recipeImageCategoryURL":"https://paleofood.io/wp-content/uploads/2016/05/garlic-shrimp-zucchini-noodle-main-800x500.jpg"
   }
]

     var categoryItems = [];

         $.each(recipe_data, function(i, item){
            if (item.recipeCategory == "4") { categoryItems.push(item); }
         });

         var similarRecipe = '';
         var randomRecipe = {};


         for(var i = 0; i < categoryItems.length; i ++) {

            randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
            categoryItems.length = 2;

            similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>' 
            + '<a href="' + randomRecipe.recipePageURL +'">' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + '</a>' 
            + '<a href="' + randomRecipe.recipePageURL +'">' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '</a>' + '</div>' ]; 
            $('#recipeSimilar').append(similarRecipe);  

        }

这是一个 fiddle :https://jsfiddle.net/wn4fmm5r/

最佳答案

选择随机项目后,只需将其从数组中删除,这样就不会再次选择它:

var randomIndex = Math.floor(Math.random()*categoryItems.length);

randomRecipe = categoryItems[randomIndex];

categoryItems.splice(randomIndex, 1);

更新的 fiddle :https://jsfiddle.net/bLpqvs4f

关于javascript - 尝试防止 DIV 中出现重复的随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256422/

相关文章:

javascript - else if 语句会导致错误,而仅使用 if 语句则不会

JQuery - 事件委托(delegate) - 我的代码中发生了什么?

php - 可编辑表格列表的插件

arrays - 按从小到大排列的元素索引

javascript - 如何在 JavaScript 中的数组中添加多个对象?

javascript - v-显示嵌套数组项是否与过滤数组匹配

javascript - 使用 javascript、范围输入和 css 转换的数学 : scale()

javascript - JS中如何下载多个文件

javascript - 简单的 jQuery 星级评分和 AngularJs (ng-repeat)

javascript - jQuery 表格行不会在表格元素内呈现