JavaScript ES2015上的第一个地图 [英] First item from a Map on JavaScript ES2015
本文介绍了JavaScript ES2015上的第一个地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个地图
这样:
const m = new Map();
m.set('key1', {})
.
m.set('keyN' {})
地图
可以有1个或多个项目。我可以通过索引获取第一个项目,而没有 m.get('key1')
并且没有迭代器循环?
the Map
can have 1 or many items. Can I get the first item by index, without m.get('key1')
and without a iterator loop?
like: m.get()[0]
推荐答案
使用 Map.prototype.entries
函数,像这样
Use the Map.prototype.entries
function, like this
const m = new Map();
m.set('key1', {})
m.set('keyN', {})
console.log(m.entries().next().value); // [ 'key1', {} ]
如果要获取第一个密钥,请使用 Map.prototype.keys
,像这样
console.log(m.keys().next().value); // key1
同样,如果你想得到第一个值,那么您可以使用 Map.prototype.values
,像这样
console.log(m.values().next().value); // {}
为什么我们必须对于返回的值,调用 next()
是所有这些函数返回迭代器。详细了解迭代协议此处。
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.
这篇关于JavaScript ES2015上的第一个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文