JavaScript ES2015 地图中的第一项 [英] First item from a Map on JavaScript ES2015

查看:22
本文介绍了JavaScript ES2015 地图中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 Map:

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

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

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

喜欢: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,像这样

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆