[英]create unique value and push to array in javascript
我需要創建一個具有唯一值的數組。 在這里,如果創建的值包含在該數組中,則需要創建另一個值並再次需要檢查該數組中是否存在新創建的值,如果再次存在則需要進行相同的檢查。
這是我嘗試過的代碼,如果我執行它,我認為會發生無限循環場景。
let arr = [];
for(let i=0; i<10;i++) {
let k = 1;
let pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
while(k > 0){
k++;
if(arr.indexOf(pass) > -1) {
pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
} else {
arr.push(pass);
break;
}
console.log(arr)
}
}
這段代碼有什么錯誤?
是的,你是對的。 這是一個無限循環。
問題是行pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a';
. 這只會生成 5 個值之一。 pass
將永遠是
因為你的數組有 10 個元素長,但你只用 5 個可能的元素填充它,你永遠無法用所有獨特的元素填充它。 所以它會 go 進入一個無限循環,試圖生成唯一元素但永遠找不到唯一元素。
您需要重寫 pass 的計算以生成 5 個以上的唯一元素。 嘗試pass = (Math.floor(Math.random() * 10))+'a';
和 go 從那里。
let arr = [(Math.floor(Math.random() * (10)))+'a']; for(let i=0; i<=10;i++) { let k = 0; let pass = (Math.floor(Math.random() * (10)))+'a'; while(k < arr.length){ k++; if(arr.indexOf(pass) > -1){ pass = (Math.floor(Math.random() * (10 - 6 + 1)) + 6)+'a'; }else { arr.push(pass); break; } } } console.log(arr)
在您的條件下,變量 k 始終 > 0 並且它無限循環。
編輯1:
答案基於@Mathew 答案更新
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.