js 字符串排序 String.prototype.localeCompare

使用JS对字符串进行排序

 

 

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

 

localeCompare 只对比传入字符串的第0个元素(如果第0个元素不同)

 

 

// 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

posted @ 2020-08-17 21:33  hh9515  阅读(1098)  评论(0编辑  收藏  举报