javascript - 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, ...]
解决方案
您可以使用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)
推荐阅读
- git - git rev-parse origin/branch_name 随机失败,并显示“致命:不明确的参数......未知的修订或路径不在工作树中”
- vue.js - Nuxt (SSR/Vuex):一旦所有组件都创建完成,就派发一个动作
- powershell - 替换数组的一个属性中的文本
- python - 在 Python 中将 for 循环转换为 map() 函数方法
- google-cloud-spanner - yugabytedb 如何保证垃圾回收时的快照一致?
- mysql - 连接两个表并使用 MySQL 连接对列求和
- android - 如何创建带有消息“您确定要删除它吗?”的窗口
- linux - mongod.service:控制进程退出,code=exited status=48
- reactjs - 反应错误甚至不做任何事情
- solana - solana-test-validator:没有这样的文件或目录恐慌