如何对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 loop)时,可以总是希望如此.
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屋!