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不是函数。如何对Set进行排序以确保特定的迭代顺序?
1 个解决方案
#1
55
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总是具有相同的迭代顺序 - 元素插入顺序[1],因此当您迭代它(通过迭代方法,通过调用Symbol.iterator或通过for ...循环)时,您总是可以期望。
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
[1] forEach和CreateSetIterator
#1
55
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总是具有相同的迭代顺序 - 元素插入顺序[1],因此当您迭代它(通过迭代方法,通过调用Symbol.iterator或通过for ...循环)时,您总是可以期望。
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
[1] forEach和CreateSetIterator