如何对 ES6 `Set` 进行排序? [英] How can I sort an ES6 `Set`?
问题描述
new Set(['b', 'a', 'c']).sort()
抛出 TypeError: set.sort is not a function
.如何对 Set
进行排序以确保特定的迭代顺序?
new Set(['b', 'a', 'c']).sort()
throws TypeError: set.sort is not a function
. How can I sort a Set
to ensure a particular iteration order?
推荐答案
集合不是有序的抽象数据结构.
A set is not an ordered abstract data structure.
A Set
然而总是具有相同的迭代顺序 - 元素插入顺序 [1],所以当你迭代它时(通过迭代方法,通过调用 Symbol.iterator
,或通过 for.. of 循环)你总是可以期待的.
A Set
however always has the same iteration order - element insertion order [1], so when you iterate it (by an iterating method, by calling Symbol.iterator
, or by a for.. of loop) you can always expect that.
您始终可以将集合转换为数组并对其进行排序.
You can always convert the set to an array and sort that.
Array.from(new Set(["b","a","c"])).sort();
[...(new Set(["b","a","c"]))].sort(); // with spread.
[1] forEach
和 CreateSetIterator一个>
这篇关于如何对 ES6 `Set` 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!