我一直在玩新的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);
}
我不知道你的意思是「不能得到它」。 HTTP://計算器。com/questions/4550505 /從數組中獲得隨機值 –
對不起,要求澄清,澄清。 –