亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

JS創建包含隨機唯一數字的對象數組

JS創建包含隨機唯一數字的對象數組

呼喚遠方 2022-06-16 17:31:02
在javascript中,我想創建一個包含20個對象的數組,其中包含1到250之間的2個隨機數。數組中的所有數字我都希望彼此唯一?;旧鲜沁@樣的:const matches = [    { player1: 1, player2: 2 },    { player1: 3, player2: 4 },    { player1: 5, player2: 6 },    { player1: 7, player2: 8 },    ...]// all unique numbers我找到了另一種方法const indexes = [];while (indexes.length <= 8) {    const index = Math.floor(Math.random() * 249) + 1;    if (indexes.indexOf(index) === -1) indexes.push(index);}但這只會返回一個數字數組:[1, 2, 3, 4, 5, 6, 7, 8, ...]
查看完整描述

2 回答

?
慕村225694

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)


查看完整回答
反對 回復 2022-06-16
?
滄海一幻覺

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);


查看完整回答
反對 回復 2022-06-16
  • 2 回答
  • 0 關注
  • 240 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號