我正在尝试显示来自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");
}
}
德玛西亚99
相关分类