我有一个字符串数组,我需要在JavaScript中排序,但以不区分大小写的方式。如何做到这一点?


当前回答

我把上面的答案包装在一个填充中,这样我就可以在字符串数组上调用.sortIgnoreCase()

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}

其他回答

现在是时候重新审视这个老问题了。

您不应该使用依赖toLowerCase的解决方案。它们效率很低,而且在某些语言(例如土耳其语)中根本不起作用。喜欢这个:

['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))

查看浏览器兼容性文档,了解灵敏度选项的所有信息。

用. tolowercase()规范.sort()中的case。

在/ /i中包装字符串。这是使用正则表达式忽略大小写的一种简单方法

我把上面的答案包装在一个填充中,这样我就可以在字符串数组上调用.sortIgnoreCase()

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}
myArray.sort(
  function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) return -1;
    if (a.toLowerCase() > b.toLowerCase()) return 1;
    return 0;
  }
);

编辑: 请注意,我最初写这篇文章是为了说明技术,而不是考虑性能。也请参考回答@Ivan Krechetov更紧凑的解决方案。