JavaScript ES2015 地图中的第一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32373301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:58:44  来源:igfitidea点击:

First item from a Map on JavaScript ES2015

javascriptdictionaryecmascript-6

提问by Philip Loger

I have a Maplike this:

我有一个Map这样的:

const m = new Map();
m.set('key1', {})
.
m.set('keyN' {})

the Mapcan have 1 or many items. Can I get the first item by index, without m.get('key1')and without a iterator loop?

Map可以有1个或多个项目。我可以通过索引获取第一个项目,没有m.get('key1')和没有迭代器循环吗?

like: m.get()[0]

喜欢: m.get()[0]

回答by thefourtheye

Use the Map.prototype.entriesfunction, like this

使用Map.prototype.entries函数,像这样

const m = new Map();
m.set('key1', {})
m.set('keyN', {})

console.log(m.entries().next().value); // [ 'key1', {} ]



If you want to get the first key, then use Map.prototype.keys, like this

如果你想获得第一个密钥,那么使用Map.prototype.keys,像这样

console.log(m.keys().next().value); // key1


Similarly if you want to get the first value, then you can use Map.prototype.values, like this

同样,如果你想获得第一个值,那么你可以使用Map.prototype.values,像这样

console.log(m.values().next().value); // {}


The reason why we have to call next()on the returned values is that, all those functions return iterators. Read more about the iteration protocol here.

我们必须调用next()返回值的原因是,所有这些函数都返回迭代器在此处阅读有关迭代协议的更多信息。

回答by loganfsmyth

For the specific example you are wondering about, destructuring would be perfect.

对于您想知道的特定示例,解构将是完美的。

let m = new Map();
m.set('key1', {});
m.set('key2', {});

let [[, obj]] = m;

e.g.

例如

let [pair] = m;
let [key, obj] = pair;

is one option to destructure and then grab the value, but the easier option would be

是解构然后获取价值的一种选择,但更简单的选择是

let [obj] = m.values();

回答by KidThePug

Also, that is correct for both Setand Map: you can convert anything to Arrayand then get any element by its index. Something like this:

此外,这对Setand都是正确的Map:您可以将任何内容转换为Array,然后通过其索引获取任何元素。像这样的东西:

const m = new Map();
m.set('key1', {});
m.set('key2', {});

console.log(Array.from(m)[0]); // ['key1', {}]

回答by Zuhair Taha

It could also done using spread feature at ES6 and next versions

它也可以在 ES6 和下一个版本中使用传播功能来完成

const m = new Map();
m.set('key1', 1);
m.set('key2', 2);

console.log([...m][0]);    // ['key1', 1]