方案1: 找到 count 个不同改的索引, 然后返回索引对应值的数组, 不同的索引使用 map 结构保证(indexCache), getRandomNumber 找到随机大于 items.length 个的数子, 大于它能保证取余的值是随机的.
function pick(count, items) {
if (count > items.length) throw new Error(`You cannot choose ${count} different things from ${items.length}`)
const indexCache = {}
const getRandomNumber = () => Math.ceil(10 ** (items.length + 1) * Math.random())
let counter = count
while (counter) {
const index = getRandomNumber() % items.length
if (indexCache[index] !== undefined) continue
indexCache[index] = null
counter--
}
return Object.keys(indexCache).map(i => items[i])
}
方案1优化:
function getRandomNumebrInRange(left, right) {
const number = Math.ceil((right - left) * Math.random()) + left
return number
}
function pick(count, items) {
const result =

本文介绍了两种在JavaScript中从数组中随机抽取指定数量且不重复元素的方案。方案一是通过创建一个索引缓存Map,找到不同的索引并返回对应的值;方案二是先打乱数组顺序,再直接截取所需长度的元素。
最低0.47元/天 解锁文章
1688

被折叠的 条评论
为什么被折叠?



