如何从 es6 Map 或 Set 中获取随机项目 [英] How get random item from es6 Map or Set

查看:31
本文介绍了如何从 es6 Map 或 Set 中获取随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目使用对象数组,我正在考虑迁移到 es6 Sets 或 Maps.

I have a project that uses arrays of objects that I'm thinking of moving to es6 Sets or Maps.

我需要快速从他们那里得到一个随机项目(对于我当前的数组来说显然是微不足道的).我该怎么做?

I need to quickly get a random item from them (obviously trivial for my current arrays). How would I do this?

推荐答案

Maps 和 Sets 不太适合随机访问.它们是有序的并且它们的长度是已知的,但是它们没有被索引以通过顺序索引进行访问.因此,要获取 Map 或 Set 中的第 N 个项目,您必须遍历它以找到该项目.

Maps and Sets are not well suited for random access. They are ordered and their length is known, but they are not indexed for access by an order index. As such, to get the Nth item in a Map or Set, you have to iterate through it to find that item.

从 Set 或 Map 中获取随机项的简单方法是获取键/项的整个列表,然后选择一个随机项.

The simple way to get a random item from a Set or Map would be to get the entire list of keys/items and then select a random one.

// get random item from a Set
function getRandomItem(set) {
    let items = Array.from(set);
    return items[Math.floor(Math.random() * items.length)];
}

<小时>

您可以制作一个同时适用于 Set 和 Map 的版本,如下所示:


You could make a version that would work with both a Set and a Map like this:

// returns random key from Set or Map
function getRandomKey(collection) {
    let keys = Array.from(collection.keys());
    return keys[Math.floor(Math.random() * keys.length)];
}

这显然不适用于大型 Set 或 Map,因为它必须迭代所有键并构建一个临时数组才能随机选择一个.

This is obviously not something that would perform well with a large Set or Map since it has to iterate all the keys and build a temporary array in order to select a random one.

由于 Map 和 Set 都具有已知大小,您还可以完全基于 .size 属性选择随机索引,然后您可以遍历 Map 或 Set 直到您到达所需的第 N 项.对于大型集合,这可能会更快一些,并且可以避免以更多代码为代价创建临时键数组,但平均而言,它仍然与集合的大小/2 成正比.

Since both a Map and a Set have a known size, you could also select the random index based purely on the .size property and then you could iterate through the Map or Set until you got to the desired Nth item. For large collections, that might be a bit faster and would avoid creating the temporary array of keys at the expense of a little more code, though on average it would still be proportional to the size/2 of the collection.

// returns random key from Set or Map
function getRandomKey(collection) {
    let index = Math.floor(Math.random() * collection.size);
    let cntr = 0;
    for (let key of collection.keys()) {
        if (cntr++ === index) {
            return key;
        }
    }
}

这篇关于如何从 es6 Map 或 Set 中获取随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆