How to get the first element of Set in ES6 ( EcmaS

2020-02-08 09:42发布

In ES6, how do we quickly get the element?

in MDN Syntax for Set, I didn't find an answer for it.

1条回答
Explosion°爆炸
2楼-- · 2020-02-08 10:09

They don't seem to expose the List to be accesible from the instanced Object. This is from the EcmaScript Draft:

23.2.4 Properties of Set Instances

Set instances are ordinary objects that inherit properties from the Set prototype. Set instances also have a [[SetData]] internal slot.

[[SetData]] is the list of Values the Set is holding.

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

Worth mention too that:

Set.prototype.values === Set.prototype.keys
查看更多
登录 后发表回答