第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果一個條件在 JavaScript 中為真,我該如何重復(fù)迭代?

如果一個條件在 JavaScript 中為真,我該如何重復(fù)迭代?

呼啦一陣風 2022-09-29 15:51:32
我正在嘗試顯示來自API的最多三個食譜,其中特別包括培根作為成分。API 只有 10 個符合此條件的配方,因此我遇到了一個問題,即如果用戶希望查看兩個或三個配方,則有時會在頁面上重復(fù)相同的配方。如何設(shè)置條件來檢查我正在生成并存儲在數(shù)組中的隨機數(shù)是否為重復(fù)值?如果重復(fù),則我希望迭代器減去 1,并且 for 循環(huán)繼續(xù)。我已經(jīng)列出了我所擁有的代碼,我感謝提供的任何反饋!// 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");    }  }
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經(jīng)驗 獲得超3個贊

您可以使用 來存儲已選擇的號碼。Set


const set = new Set;

//....

if (set.has(randomNumber)){

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

   i--;

} else {

   set.add(randomNumber);

//...

或者,正如 Barmar 所建議的那樣,您可以事先將整數(shù)數(shù)組從 0 洗牌到 9,然后循環(huán)訪問這些值以提高效率。下面我提供了一個使用費舍爾-耶茨洗牌的例子。


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...

}


查看完整回答
反對 回復(fù) 2022-09-29
  • 1 回答
  • 0 關(guān)注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號