2017-02-13 78 views
1

我一直在玩新的ES6 Map(),只是爲了習慣它,現在我們可以得到它的大小,我發現我可以有效地隨機抽取一張地圖,看看它是什麼看起來像。能訪問由ES6'Map'對象的keys()方法返回的數組嗎?

很明顯,可以遍歷所有條目,然後選擇隨機樣本。但是這對於大型地圖來說並不吸引人。

最後有一些代碼通過利用地圖的新可用大小來實現此目的。它比複製效率稍高,但仍然沒有吸引力。

但Map方法keys()返回一個迭代器對象,它的next()方法通常用於迭代Map實例。並且,它還包含所有條目的數組。這顯示在Chrome Devtools輸出的摘要如下:

coinNames.keys() 
MapIterator 
"keys" 
.... 
[[Entries]] 
: 
Array[7] 
0 
: 
30 
1 
: 
12 

... (entries omitted) 

length 
: 
7 

我找不到如何訪問這個數組,以便找到由數組索引的條目。

下面的代碼(給出get_random_integer()和report()...)的代碼(相當毫無意義,但是是說明性的)。

函數play()在按鈕按下時調用,並記錄一個隨機名稱。

但是,最好不要迭代,只需要獲取數組中給定位置的條目。

任何想法?

function CoinName(name, slang, plural) { 
    this.name = name; 
    this.plural = plural; 
} 
const coinNames = new Map(); 

window.onload = init; 
function init() { 
    report ('OK'); 
    var button = document.getElementById('buttonA'); 
    button.addEventListener('click', play); 

    coinNames.set(30, new CoinName('half crown')); 
    coinNames.set(12, new CoinName('shilling', 'bob')); 
    coinNames.set(3, new CoinName('threepenny bit')); 
    coinNames.set(6, new CoinName('sixpence', 'tanner')); 
    coinNames.set(1, new CoinName('penny', '', 'pence')); 
    coinNames.set(1/4, new CoinName('farthing')); 
    coinNames.set(1/2, new CoinName('halfpenny', 'hapeny', 
          'halfpence')); 
} 

function getRandomKey() { 
    let requiredIndex = get_random_integer(0, coinNames.size); 

    let keys = coinNames.keys(); 
    let found = undefined; 
    let goon = true; 
    let i = 0; 
    while(goon) { 
     goon = keys.next().value; 
     //report(goon); 
     if(goon && i===requiredIndex) { 
      found = goon; 
      goon = false; 
     } 
     i += 1;  
    } 
    return found; 
} 

function play() { 
    let key = getRandomKey(); 
    let entry = coinNames.get(key); 
    report(entry.name); 
} 
+2

我不知道你的意思是「不能得到它」。 HTTP://計算器。com/questions/4550505 /從數組中獲得隨機值 –

+0

對不起,要求澄清,澄清。 –

回答

1

如果我正確理解你的問題,你只是想從一個Map對象中獲得一個隨機密鑰。

,我能想到的來完成,這簡單的方法是通過Map#keys返回的迭代器對象投射到一個數組(使用擴頻操作者...,或Array.from),然後簡單地訪問隨機索引

const map = [['a','1'],['b','2'],['c','3']].reduce((m, e) => m.set(...e), new Map()); 
 
const getRandKey = map => [...map.keys()][Math.floor(Math.random() * 1000) % map.size]; 
 
let i = 10; while(i-- > 0) console.log(getRandKey(map));

+0

謝謝,很值得聽到傳播... –

-3

我同意上面的意見,如果您可以提供更多的上下文將是有幫助的。這就是說,如果你想遍歷一個對象的鍵,你需要一個數組。要創建的按鍵陣列可以使用Object.keys()https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

const america = { 
    California: "Sacramento", 
    NewYork: "New York", 
    Texas: "Austin" 
} 

const capitals = (america) => { 
    let result = [] 
    for (var key in america) { 
    result.push(america[key]) 
    } 
    return result; 
} 
console.log(capitals(america)) 

const states = Object.keys(america) 
console.log(states); 
1

您可以使用傳播元素轉換MapArrayArray.prototype.entries()拿到鑰匙,值對數組。

const map = new Map; 
 

 
map.set(2, {abc:123}); 
 
map.set(7, {def:456}); 
 
map.set(1, {ghi:789}); 
 

 
let entries = [...map]; 
 
let len = entries.length; 
 
let key = Math.floor(Math.random() * len); 
 
let [prop, value] = entries[key]; 
 

 
console.log(prop, value);