我尝试按字母顺序对数组数据进行排序,但我认为有些不对劲。
var items;
// it's OK
items = ['a', 'á'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["a", "á"]
// it's OK, too
items = ['an', 'án'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["an", "án"]
// hmmm, it's not
items = ['an', 'ál'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["ál", "an"]
匈牙利字母以 a、á、b、c 开头...
任何建议,我应该如何使用 localecompare 功能。
最佳答案
如果没有办法用 localeCompare
做到这一点,似乎您必须编写自己的排序器:
const alphabet = "aábcdefghijklmnopqrstuvwxyz";
function alphabetically(a, b) {
a = a.toLowerCase(), b = b.toLowerCase();
// Find the first position were the strings do not match
let position = 0;
while(a[position] === b[position]) {
// If both are the same don't swap
if(!a[position] && !b[position]) return 0;
// Otherwise the shorter one goes first
if(!a[position]) return 1;
if(!b[position]) return -1;
position++;
}
// Then sort by the characters position
return alphabet.indexOf(a[position]) - alphabet.indexOf(b[position]);
}
可用作
array.sort(alphabetically);
关于javascript - 为什么 localeCompare 不像我期望的那样工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51599040/