better2021 / Blog

个人博客
https://feiyuweb.me/Blog
1 stars 0 forks source link

使用localeCompare() 方法来实现中文按照拼音排序,方法相当简单 #49

Open better2021 opened 3 years ago

better2021 commented 3 years ago
var array = ['白鸽', '麻雀', '大象', '狗', '猫', "鸡"];
array = array.sort(function compareFunction(a, b) {
    return a.localeCompare(b);
});
console.log(array ) //  ['白鸽', '大象', '狗', '鸡', '麻雀', '猫']
array = array.sort(function compareFunction(a, b) {
    return b.localeCompare(a);
});
console.log(array )  // ['猫', '麻雀', '鸡', '狗', '大象', '白鸽']