【问题标题】:JS Create array of objects containing random unique numbersJS 创建包含随机唯一数字的对象数组
【发布时间】:2020-04-07 18:20:06
【问题描述】:

在 javascript 中,我想创建一个包含 20 个对象的数组,其中包含 2 个介于 1 和 250 之间的随机数。数组中的所有数字都希望彼此唯一。基本上是这样的:

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, ...]

【问题讨论】:

  • 您好 dubs_tep,如果此页面上的答案解决了您的问题,请考虑将其标记为已接受。谢谢

标签: javascript arrays object unique


【解决方案1】:

您可以使用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)

【讨论】:

    【解决方案2】:

    您可以创建一个包含 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2011-08-06
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      相关资源
      最近更新 更多