我一直在玩新的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 /从数组中获得随机值 –
对不起,要求澄清,澄清。 –