new Set(['b', 'a', 'c']).sort()
抛出TypeError: set.sort is not a function
。如何对 Set
进行排序以确保特定的迭代顺序?
集合不是有序的抽象数据结构。
然而A
Set
始终具有相同的迭代顺序 - 元素插入顺序 [1],因此当您迭代它时(通过迭代方法,通过调用 Symbol.iterator
,或通过 for..of 循环),您总是可以期望那个。
您始终可以将集合转换为数组并对其进行排序。
Array.from(new Set(["b","a","c"])).sort();
[...(new Set(["b","a","c"]))].sort(); // with spread.
forEach
和 CreateSetIterator
在某些情况下,最好对集合进行就地“排序”,类似于
array.sort()
,可以这样做:
function sortSet(set) {
const entries = [];
for (const member of set) {
entries.push(member);
}
set.clear();
for (const entry of entries.sort()) {
set.add(entry);
}
return set;
};
sortSet(new Set([3,2,1]))
// => Set(3) { 1, 2, 3 }
最简单的方法是。
console.log(new Set(['b', 'a', 'c'].sort()))
//Set(3) {"a", "b", "c"}
.sort 函数是一个高阶函数,这意味着它内部可以有另一个函数。首先,只有 .sort() 可以处理字符或字符串,但它会给数字带来错误。我在视频中讨论了集合和排序功能。我希望你能理解。 https://www.youtube.com/watch?v=ztw4Gh8eogw
//This is sort() for getting numbers in ascending order:
const setC = new Set(([58,12,11,10,5,32]).sort((a,b)=>a -b));
//This is sort() for getting numbers in descending order:
const setC = new Set(([58,12,11,10,5,32]).sort((a,b)=>b -a));
//This is sort() for strings
const setD=new Set((['mangoes','bananas', 'apples','oranages']).sort());
// This is sort() for characters
const setD=new Set((['m', 'b', 'a', 'r']).sort());
You can convert the set to an array too and then sort it but that is not
required in your case.
const arrayofsetA = Array.from(setA);
//for strings or characters
arrayofsetA.sort();
//for numbers or floating point numbers
arrayofsetA.sort((a,b) => a-b);
const set1 = new Set(['b', 'c', 'a']);
// Sort the elements and create a new Set
const sortedSet = new Set([...set1].sort());
console.log([...sortedSet]); // ['a', 'b', 'c']