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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:37:51  来源:igfitidea点击:

How can I sort an ES6 `Set`?

javascriptarrayssortingsetecmascript-6

提问by ericsoco

new Set(['b', 'a', 'c']).sort()throws TypeError: set.sort is not a function. How can I sort a Setto 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 Sethowever 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] forEachand CreateSetIterator

[1]forEachCreateSetIterator