Javascript 如何对 ES6 `Set` 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33089695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort an ES6 `Set`?
提问by ericsoco
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?
new Set(['b', 'a', 'c']).sort()
抛出TypeError: set.sort is not a function
。如何对 aSet
进行排序以确保特定的迭代顺序?
回答by Benjamin Gruenbaum
A set is not an ordered abstract data structure.
集合不是有序的抽象数据结构。
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.
Set
然而,A始终具有相同的迭代顺序 - 元素插入顺序 [1],因此当您对其进行迭代时(通过迭代方法、调用Symbol.iterator
或 for.. of 循环),您总是可以期待这一点。
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
and CreateSetIterator