我有一个字符串数组,我需要在JavaScript中排序,但以不区分大小写的方式。如何做到这一点?
当前回答
现在是时候重新审视这个老问题了。
您不应该使用依赖toLowerCase的解决方案。它们效率很低,而且在某些语言(例如土耳其语)中根本不起作用。喜欢这个:
['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))
查看浏览器兼容性文档,了解灵敏度选项的所有信息。
其他回答
用. tolowercase()规范.sort()中的case。
你也可以使用Elvis操作符:
arr = ['Bob', 'charley', 'fudge', 'Fudge', 'biscuit'];
arr.sort(function(s1, s2){
var l=s1.toLowerCase(), m=s2.toLowerCase();
return l===m?0:l>m?1:-1;
});
console.log(arr);
给:
biscuit,Bob,charley,fudge,Fudge
localeCompare方法可能很好…
注意:Elvis操作符是if then else的“三元操作符”的缩写形式,通常带有赋值。 如果你从侧面看,它看起来像猫王… 例如:
if (y) {
x = 1;
} else {
x = 2;
}
你可以使用:
x = y?1:2;
也就是说,当y为真时,则返回1(用于赋值给x),否则返回2(用于赋值给x)。
我把上面的答案包装在一个填充中,这样我就可以在字符串数组上调用.sortIgnoreCase()
// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
Array.prototype.sortIgnoreCase = function () {
return this.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
};
}
在(几乎:)一行代码中
["Foo", "bar"].sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
结果是
[ 'bar', 'Foo' ]
而
["Foo", "bar"].sort();
结果
[ 'Foo', 'bar' ]
其他答案假设数组包含字符串。我的方法更好,因为即使数组包含null、undefined或其他非字符串,它也能工作。
var notdefined;
var myarray = ['a', 'c', null, notdefined, 'nulk', 'BYE', 'nulm'];
myarray.sort(ignoreCase);
alert(JSON.stringify(myarray)); // show the result
function ignoreCase(a,b) {
return (''+a).toUpperCase() < (''+b).toUpperCase() ? -1 : 1;
}
null将在'nulk'和'nulm'之间排序。但未定义的总是排在最后。