如果一个条件在 JavaScript 中为真,我该如何重复迭代?

我正在尝试显示来自API的最多三个食谱,其中特别包括培根作为成分。API 只有 10 个符合此条件的配方,因此我遇到了一个问题,即如果用户希望查看两个或三个配方,则有时会在页面上重复相同的配方。如何设置条件来检查我正在生成并存储在数组中的随机数是否为重复值?如果重复,则我希望迭代器减去 1,并且 for 循环继续。我已经列出了我所拥有的代码,我感谢提供的任何反馈!


// The number of recipes the user would like to display//

var recipeNumber = $("#recipe-input").val();

var parsedInput = parseInt(recipeNumber);


// creating an empty array that will story the random numbers that are generated//

var ranNumArr = [];

console.log(ranNumArr);


for (i = 0; i < parsedInput; i++) {

  // generate a random number based on the length of the recipe API's array of bacon recipes (10) and push it into the ranNumArr// 

  var randomNumber = Math.floor(Math.random() * 10);

  ranNumArr.push(randomNumber);


  // If the value of the index in the array is equal to a previous index's value, repeat the iteration//

  if (ranNumArr[i] === ranNumArr[i -1] || ranNumArr[i] === ranNumArr[i -2]){

      console.log("this is a duplicate number")

      i = i - 1

    }

  // else, display the recipe on the card//

  else  {

      randomRecipe = ranNumArr[i]

 // Create cards that will house the recipes//

      var recipeCell = $("<div>").attr("class", "cell");

      $("#recipes-here").append(recipeCell);

      var recipeCard = $("<div>").attr("class", "card");

      recipeCell.append(recipeCard);

      var recipeSection = $("<div>").attr("class", "card-section");

      recipeCard.append(recipeSection);  

      var cardTitleE1 = $("<h1>"); 

      cardTitleE1.attr("id", "recipe-title"); 

      var cardImageE1 = $("<img>"); 

      cardImageE1.attr("id", "recipe-image"); 

      var cardTextE1 = $("<a>"); 

      cardTextE1.attr("id", "recipe-link");

    }

  }


呼啦一阵风
浏览 88回答 1
1回答

德玛西亚99

您可以使用 来存储已选择的号码。Setconst set = new Set;//....if (set.has(randomNumber)){&nbsp; &nbsp;console.log("this is a duplicate number");&nbsp; &nbsp;i--;} else {&nbsp; &nbsp;set.add(randomNumber);//...或者,正如 Barmar 所建议的那样,您可以事先将整数数组从 0 洗牌到 9,然后循环访问这些值以提高效率。下面我提供了一个使用费舍尔-耶茨洗牌的例子。const arr = [...Array(10).keys()];for (let i = arr.length - 1; i > 0; i--) {&nbsp; &nbsp; const j = Math.random() * (i + 1) | 0;&nbsp; &nbsp; const temp = array[i];&nbsp; &nbsp; array[i] = array[j];&nbsp; &nbsp; array[j] = temp;}for(const num of arr){&nbsp; &nbsp;//do something with num...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript