首页 > 解决方案 > JS创建包含随机唯一数字的对象数组

问题描述

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

标签: javascriptarraysobjectunique

解决方案


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


推荐阅读