如何在 ES6中获得 Set 的第一个元素(EcmaScript2015)

在 ES6中,如何快速获得元素?

集合的 MDN 语法中,我没有找到答案。

77441 次浏览

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

Another choice will be to use the for..of loop like so:

const mySet = new Set(["one", "two", 3]);
for (let item of mySet) {
console.log(item);
break;
}

A more direct way to get the first element from a Set (works for arrays too):

const mySet = new Set(['foo', 'bar', 'baz'])
const [firstElement, secondElement, thirdElement] = mySet


console.log(thirdElement, firstElement, secondElement) // baz foo bar

The best way is to use the iterator on the Set<T>:

const mySet = new Set<string>(['one', 'two', 'three']);
const firstValue = mySet.values().next().value;
console.log(firstValue);

You could also covert it to an array and then use normal indexing:

const mySet = new Set<string>(['one', 'two', 'three']);
const firstValue = Array.from(mySet)[0];
console.log(firstValue);

The first way is better from a complexity standpoint because it doesn't have to create a new array.

The most elegant and practical solution I have found is by retrieving the first IteratorResult and acquiring its value set.values().next().value.

const set = new Set([0, 1, 2, 3, 4]);
const first = set.values().next().value; // first will be equal to 0

there are many solutions

  1. for...of loop

const set = new Set();
set.add(2);
set.add(3);


// return the first item of Set ✅
function getFirstItemOfSet(set) {
for(let item of set) {
if(item) {
return item;
}
}
return undefined;
}


const first = getFirstItemOfSet(set);
console.log('first item =', first);

  1. destructuring assignment

const set = new Set();
set.add(2);
set.add(3);


// only get the first item ✅
const [first] = set;
console.log('first item =', first);

  1. ...spread operator

const set = new Set();
set.add(2);
set.add(3);


// convert Set to Array ✅
const first = [...set][0];
console.log('first item =', first);

  1. iterator & next()

const set = new Set();
set.add(2);
set.add(3);


// iterator ✅
const first = set.keys().next().value;
console.log(`first item =`, first);


// OR
set.values().next().value;


// OR
set.entries().next().value[0];
// OR
set.entries().next().value[1];

refs

https://www.cnblogs.com/xgqfrms/p/16564519.html