簡體   English   中英

如何從地圖Ecma6對象中提取隨機物品?

[英]how to pickup a random item from a Map Ecma6 object?

map = new Map([
    [ 1, 'one' ],
    [ 2, 'two' ],
    [ 3, 'three' ], 
]);

如何從地圖中檢索隨機項目?

function nth(x, iterable) {
    for (const el of iterable)
        if (x-- == 0)
            return el;
    throw new Error("not found");
}

console.log(nth(Math.floor(Math.random() * map.size), map.values())) // or keys or entries

您可以先獲取數組中映射的值,然后將數組的長度作為隨機因子,並在隨機索引處獲取值。

 var map = new Map([[1, 'one'], [2, 'two'], [3, 'three']]), values = [...map.values()], random = values[Math.floor(Math.random() * values.length)]; console.log(random); 

假設Map中的鍵是連續的,您將獲得一個介於1Map.length之間的隨機數,然后從Map中檢索與該隨機數相對應的值。

 map = new Map([ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ], ]); const rand = Math.floor(Math.random() * map.size) + 1; const randomFromMap = map.get(rand); console.log(randomFromMap); 

如果鍵不是連續的或不是整數,則需要使用Map.prototype.keys()將鍵作為數組返回,然后使用來自keys數組的隨機元素檢索隨機元素。 就像是:

 const map = new Map([ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ], ]); const rand = Math.floor(Math.random() * map.size); const mapKeys = Array.from(map.keys()); console.log(map.get(mapKeys[rand])) 

從地圖創建一個數組,然后選擇一個隨機鍵。 您可以使用Math.round(Math.random() * (array.length - 1))為數組創建一個“骰子”值。

 map = new Map([ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ], ]); let array = Array.from(map); let dice = Math.round(Math.random() * (array.length - 1)) let value = array[dice]; // value contains an array with key/value pair. console.log(value); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM