2 回答

TA貢獻1880條經驗 獲得超4個贊
您可以使用Array.from方法來創建對象數組,然后還可以創建將使用while循環并Set生成隨機數的自定義函數。
const set = new Set()
function getRandom() {
let result = null;
while (!result) {
let n = parseInt(Math.random() * 250)
if (set.has(n)) continue
else set.add(result = n)
}
return result
}
const result = Array.from(Array(20), () => ({
player1: getRandom(),
player2: getRandom()
}))
console.log(result)

TA貢獻1824條經驗 獲得超5個贊
您可以創建一個包含 251 個元素 (0-250) 的數組并將所有值預設為 0 以跟蹤生成的元素。生成一個值后,將該數組中的值標記為 1。
檢查以下:
// create an array of 251 elements (0-250) and set the values to 0
let array = Array.from({ length: 251 }, () => 0);
let matches = [];
function getRandomUniqueInt() {
// generate untill we find a value which hasn't already been generated
do {
var num = Math.floor(Math.random() * 249) + 1;
} while(array[num] !== 0);
// mark the value as generated
array[num] = 1;
return num;
}
while (matches.length <= 4) {
let obj = { "player1" : getRandomUniqueInt(), "player2" : getRandomUniqueInt() };
matches.push(obj);
}
console.log(matches);
添加回答
舉報