我一直在使用新的ES6地图(),只是为了适应它,现在我们可以获得大小,我突然想到可以有效地对地图进行随机采样,看看它是什么样子。
显然,可以遍历,生成一个包含所有条目的数组,然后选择随机样本。但这对于大型地图来说并不吸引人。
在最后有一些代码,它通过利用地图的新可用大小来实现这一点。它比复制的效率稍高一些,但仍然没有吸引力。
但是Map方法键()返回一个迭代器对象,我们通常使用它的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);
}发布于 2017-02-19 02:15:25
如果我没理解错的话,您只是想从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));
发布于 2017-02-20 15:41:48
您可以使用扩展元素将Map转换为Array,使用Array.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);
发布于 2017-02-18 02:16:24
[[Entries]]是迭代器的一个不可访问的internal slot。这是一个实现细节,甚至不是由language standard指定的。你拿不到的。
https://stackoverflow.com/questions/42210807
复制相似问题