为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 329 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号