可以访问ES6' Map'的key()方法返回的数组。对象?

时间:2017-02-13 18:18:14

标签: javascript dictionary

我一直在玩新的ES6 Map(),只是为了习惯它,而且,现在我们可以得到它的大小,我想到一个人可以有效地随机抽取一张地图,到看看它的样子。

显然,可以迭代,制作所有条目的数组,然后选择随机样本。但这对大型地图来说没有吸引力。

最后有一些代码通过利用新的可用地图大小来实现这一目标。它比复制稍微有效,但仍然没有吸引力。

但是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()...)。

按下按钮时会调用pl​​ay()函数,并记录一个随机名称。

但是,最好不要迭代,只是获取数组中给定位置的条目。

有什么想法吗?

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);
}

4 个答案:

答案 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));

答案 1 :(得分:1)

您可以使用spread元素将Map转换为ArrayArray.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);

答案 2 :(得分:0)

[[Entries]]是迭代器无法访问的JPA using multiple database schemas。它是一个实现细节,甚至没有internal slot指定。你无法得到它。

答案 3 :(得分:-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);