如何对 ES6 `Set` 进行排序? [英] How can I sort an ES6 `Set`?

查看:37
本文介绍了如何对 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 循环)你总是可以期待的.

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] forEachCreateSetIterator

这篇关于如何对 ES6 `Set` 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆