[英]JavaScript's sort method handling of capital letters
Noticed something potentially odd with JavaScript's sort()
method. 使用JavaScript的sort()
方法注意到一些奇怪的东西。 Given the following array: 给出以下数组:
var arr = ['Aaa',
'CUSTREF',
'Copy a template',
'Copy of Statementsmm',
'Copy1 of Default Email Template',
'Copy11',
'Cust',
'Statements',
'zzzz'];
Calling sort on this array: 在此数组上调用sort:
console.log(arr.sort());
Yields: 产量:
["Aaa", "CUSTREF", "Copy a template", "Copy of Statementsmm", "Copy1 of Default Email Template", "Copy11", "Cust", "Statements", "zzzz"]
Is this correct? 它是否正确? ie. 即。 CUSTREF
is listed first, is this because of it's capital letters? CUSTREF
首先列出,这是因为它的大写字母?
That is correct. 那是正确的。 The strings are being sorted in a binary fashion, using the ordinal values of the characters themselves. 使用字符本身的序数值以二进制方式对字符串进行排序。
For a case-insensitive sort, try this: 对于不区分大小写的排序,请尝试以下操作:
arr.sort(function(a,b) {
a = a.toLowerCase();
b = b.toLowerCase();
if( a == b) return 0;
return a < b ? -1 : 1;
});
You are correct, it is because of capital letters. 你是对的,这是因为大写字母。 If you are sorting strings which might have non ASCII characters such as ä and ö you should use String.localeCompare() . 如果要排序可能具有非ASCII字符的字符串,例如ä和ö,则应使用String.localeCompare() 。 This also fixes the capital letter problem. 这也解决了大写字母问题。
arr.sort(function (a, b) {
return a.localeCompare(b);
});
Yes, It has a higher Unicode value. 是的,它具有更高的Unicode值。 (it = the 'U' in the first word) (它=第一个单词中的'U')
you maybetter use 你可能会更好用
.sort(function(a,b) { return (a.toLowerCase() < b.toLowerCase()) ? -1 : 1;});
如果你看一下他们对字符进行编码的方式(例如ASCII表),你会看到,大写字母的值较低,小写一个,所以是 - 这是因为大写字母
Since U
(U+0055) has a lesser Unicode value than o
(U+006F), a case-sensitive sort
will always place U
before o
. 由于U
(U + 0055)的Unicode值小于o
(U + 006F),因此区分大小写的sort
将始终将U
置于o
之前。 For a case-insensitive sort
, you should try: 对于不区分大小写的sort
,您应该尝试:
arr.sort(
function(a, b){
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.