我有一个字符串数组,我需要在JavaScript中排序,但以不区分大小写的方式。如何做到这一点?
当前回答
用. tolowercase()规范.sort()中的case。
其他回答
在(几乎:)一行代码中
["Foo", "bar"].sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
结果是
[ 'bar', 'Foo' ]
而
["Foo", "bar"].sort();
结果
[ 'Foo', 'bar' ]
arr.sort(function(a,b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a == b) return 0;
if (a > b) return 1;
return -1;
});
在/ /i中包装字符串。这是使用正则表达式忽略大小写的一种简单方法
如果不管输入数组中元素的顺序如何,你都想保证相同的顺序,这里是一个稳定排序:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
你也可以使用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)。