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
First item from a Map on JavaScript ES2015
提问by Philip Loger
I have a Map
like this:
我有一个Map
这样的:
const m = new Map();
m.set('key1', {})
.
m.set('keyN' {})
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?
在Map
可以有1个或多个项目。我可以通过索引获取第一个项目,没有m.get('key1')
和没有迭代器循环吗?
like: m.get()[0]
喜欢: m.get()[0]
回答by thefourtheye
Use the Map.prototype.entries
function, 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.
回答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 Set
and Map
: you can convert anything to Array
and then get any element by its index. Something like this:
此外,这对Set
and都是正确的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]