Array.prototype.sort()字母排序

2019-07-021616次阅读javascript

我们都知道Array.prototype.sort()对数字大小排序a-b是升序排序,b-a是降序排序。

[10, 5, 40, 25, 1].sort((a,b)=>a-b)
//[1, 5, 10, 25, 40]

[10, 5, 40, 25, 1].sort((a,b)=>b-a)
//[40, 25, 10, 5, 1]

其实Array.prototype.sort()默认就是根据字符串Unicode码点排序的。可以说对字母字符串默认是升序排序的。

['c','g','a','h'].sort()
//["a", "c", "g", "h"]

//降序呢还是b-a
['c','g','a','h'].sort( (a,b)=>b.charCodeAt() - a.charCodeAt() )
//["h", "g", "c", "a"]

String.prototype.charCodeAt(index)方法返回0到65535之间的整数,参数index是一个大于等于0,小于字符串长度的整数。如果不是一个数值,则默认为0。

上一篇: Sass中半透明@include  下一篇: Node核心API的path模块学习  

Array.prototype.sort()字母排序相关文章