抱歉,如果這是一個新手問題,我正在嘗試將三個字串放入大小為 9 的陣列中,該陣列將三個字串放置在陣列中的隨機索引處,但我嘗試這樣做會導致無限回圈
const ticketArray = [];
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"];
const threeOfThem = [];
let arr = []
let randStr = "";
for (let i = 0; i < 3; i ) {
threeOfThem[i] = victoryMultipliers[Math.floor(Math.random() * victoryMultipliers.length)]
randStr = threeOfThem[i]
//console.log(randStr)
arr = threeOfThem.filter(val => val === randStr)
if (arr.length >= 2) {
threeOfThem.pop();
i--;
}
}
const threeTicketArray = threeOfThem;
/// So above we have an array of example ["x20", "x50", "x30"]
// so below is where we have some problem
let randInt;
let tempStr = "";
for (let i = 0; i < 10; i ) { // i want to make an array.length of 9
randInt = Math.floor( Math.random() * 3 );
tempStr = threeTicketArray[randInt]; // to find the "x30" or whichever i stored
ticketArray.push(tempStr); // push it into the ticketArray
let len = ticketArray.filter(val => val === tempStr) // we filter to bring out the once for this loops iteration
if ( len.length > 3 ) { // if I have 4 of example "x30"
ticketArray.pop(); // I remove it as it was the last "x30" string added to the array
i--; // I subtract the iteration by 1 so I can restart the this iteration of the loop
}
}
// the end of the loop
console.log(ticketArray);
所以隨機我希望ticketArray的大小為9,票字串被放置在隨機索引中,每個字串出現3次
但我得到了無限回圈,我不明白為什么!
請幫忙,因為我沒有想法 atm
uj5u.com熱心網友回復:
請參閱下面的解決方案,并告訴我您的想法
const ticketArray = [];
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"];
const threeOfThem = [];
let arr = []
let randStr = "";
for (let i = 0; i < 3; i ) {
threeOfThem[i] = victoryMultipliers[Math.floor(Math.random() * victoryMultipliers.length)]
randStr = threeOfThem[i]
//console.log(randStr)
arr = threeOfThem.filter(val => val === randStr)
if (arr.length >= 2) {
threeOfThem.pop();
i--;
}
}
const threeTicketArray = threeOfThem;
/// So above we have an array of example ["x20", "x50", "x30"]
// so below is where we have some problem
let randInt;
let tempStr = "";
for (let i = 0; i < 10; i ) { // i want to make an array.length of 9
randInt = Math.floor( Math.random() * 3 );
tempStr = threeTicketArray[randInt]; // to find the "x30" or whichever i stored
ticketArray.push(tempStr); // push it into the ticketArray
let len = ticketArray.filter(val => val === tempStr) // we filter to bring out the once for this loops iteration
if ( len.length > 3 ) { // if I have 4 of example "x30"
ticketArray.pop();
// this should solve the infinit loop issue.
// as it seems that randInt is generating dublicated.
if (ticketArray.length <9)
i--
}
}
// the end of the loop
console.log(ticketArray);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490878.html
標籤:javascript 数组 循环
