【问题标题】:How do I repeat an iteration if a condition is true in JavaScript?如果 JavaScript 中的条件为真,我如何重复迭代?
【发布时间】:2020-09-30 11:38:30
【问题描述】:

我正在尝试显示来自 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");

      // Adding the recipe title, url, and image from the API call//
      cardTitleE1.text(response.hits[randomRecipe].recipe.label);
      cardTextE1.text("Click here for link to recipe");
      cardTextE1.attr("href", response.hits[randomRecipe].recipe.url);
      cardTextE1.attr("target", "_blank");
      cardImageE1.attr("src", response.hits[randomRecipe].recipe.image);

      // Display the recipe on the DOM//
      recipeSection.append(cardTitleE1); 
      recipeSection.append(cardImageE1);
      recipeSection.append(cardTextE1); 
    }
  }

【问题讨论】:

  • 不要在循环中选择随机数。制作一个包含所有数字的数组并打乱它,然后遍历数组。

标签: javascript jquery arrays conditional-statements


【解决方案1】:

您可以使用Set 来存储已选择的号码。

const set = new Set;
//....
if (set.has(randomNumber)){
   console.log("this is a duplicate number");
   i--;
} else {
   set.add(randomNumber);
//...

或者,正如Barmar 建议的那样,您可以预先将整数数组从 0 打乱到 9,然后循环这些值以提高效率。下面我提供了一个使用 Fisher-Yates shuffle 的示例。

const arr = [...Array(10).keys()];
for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.random() * (i + 1) | 0;
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
for(const num of arr){
   //do something with num...
}

【讨论】:

  • 谢谢你们!通过阵列洗牌解决了我的问题!我还是个新手,看到如何在数组中洗牌的语法非常有帮助。
  • @katlinking29 很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多