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

查看:324
本文介绍了如何对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 loop)时,可以总是希望如此.

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] forEach CreateSetIterator

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

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