js 字符串排序 String.prototype.localeCompare

使用JS对字符串进行排序

注意,在这个数组里,先将数字转为字符串(只有字符串才有localCompare这个方法)

localeCompare 只对比了字符串的第0个元素,  3 2 1...  1,2,3 ...

// In implementations which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent.

如果不指定第二个参数(语言类型),那么表现是由实现决定,随机的(文档上这么说)

const city = ['澳门','上海','北京']

city.sort((a,b)=>a.localeCompare(b,'zh-CN')) // 这里一定要传第二个参数

["澳门", "北京", "上海"] // a b c 拼音顺序

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

原文地址:https://www.cnblogs.com/eret9616/p/13520243.html