问题描述
在 ES6 中,我们如何快速获取元素?
In ES6, how do we quickly get the element?
在集的MDN语法中,我没有找不到答案.
in MDN Syntax for Set, I didn't find an answer for it.
推荐答案
他们似乎没有将 List 公开为可从实例化对象访问.这是来自 EcmaScript 草案:
They don't seem to expose the List to be accesible from the instanced Object. This is from the EcmaScript Draft:
23.2.4 集合实例的属性
Set 实例是从 Set 原型继承属性的普通对象.Set 实例也有一个 [[SetData]] 内部槽.
Set instances are ordinary objects that inherit properties from the Set prototype. Set instances also have a [[SetData]] internal slot.
[[SetData]] 是集合持有的值列表.
[[SetData]] is the list of Values the Set is holding.
一种可能的解决方案(有点昂贵)是获取一个迭代器,然后调用 next()
获取第一个值:
A possible solution (an a somewhat expensive one) is to grab an iterator and then call next()
for the first value:
var x = new Set();
x.add(1);
x.add({ a: 2 });
//get iterator:
var it = x.values();
//get first entry:
var first = it.next();
//get value out of the iterator entry:
var value = first.value;
console.log(value); //1
值得一提的是:
Set.prototype.values === Set.prototype.keys
这篇关于如何在 ES6 (EcmaScript 2015) 中获取 Set 的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!