【问题标题】:Javascript Array sort() does not sort array of strings correctly [duplicate]Javascript Array sort()无法正确排序字符串数组[重复]
【发布时间】:2019-01-18 15:51:42
【问题描述】:

我有以下 JavaScript 代码:

   const ary = ["Kevin", "brandy", "Andrew"];
   const nary = ary.sort();
   console.log(nary);

我希望上述代码的输出是["Andrew","brandy", "Kevin"],即根据字典的单词顺序。

但是在控制台中我得到了输出:

    ["Andrew","Kevin","brandy"]

当我将"brandy" 中的b 切换为大写B,并再次运行代码时,

     const ary = ["Kevin", "Brandy", "Andrew"];
     const nary = ary.sort();
     console.log(nary);

输出如预期:

["Andrew","Brandy","Kevin"]

即根据单词的字典顺序。

即优先排序首字母为大写的单词,再排序首字母为小写的单词。

我的问题是:

  1. 为什么在 JavaScript 中会发生这种情况?

  2. 如何使用sort()函数根据字典的单词顺序对字符串数组["Kevin", "brandy", "Andrew"]进行排序?

Input code:

   const ary = ["Kevin", "brandy", "Andrew"];
   const nary = ary.sort();
   console.log(nary);   

Console Output: 
   ["Andrew","Kevin","brandy"]

I want the Output as:

   ["Andrew","brandy", "Kevin"]

【问题讨论】:

  • 这个问题已经有几个答案了,这里有一个候选人stackoverflow.com/questions/8996963/…
  • 对于您的第 1 点,在控制台中键入 "a" > "B"。或"a".codePointAt(0) & "B".codePointAt(0)

标签: javascript arrays sorting


【解决方案1】:

这是因为当没有提供回调函数时,元素在转换为 UTF-16 代码单元后进行排序。在您的情况下,这可能是 Kelvin 的 utf 转换字符串在 brandy 之前的原因,因此它按该顺序排序。

使用localeCompare

const ary = ["Kevin", "brandy", "Andrew"];
const nary = ary.sort(function(a, b) {
  return a.localeCompare(b)

});
console.log(nary);

【讨论】:

    【解决方案2】:

    一个班轮答案是localeCompare()

    const ary = ["Kevin", "brandy", "Andrew"];
    ary.sort(function (a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
    console.log(ary);

    【讨论】:

      【解决方案3】:

      只需先将密钥转换为lowerCase,以便密钥不区分大小写。而发生这种情况的原因是因为Javascript比较的方式ie.['a'Local compare。根据浏览器设置进行比较。

      let arr = ["Andrew","brandy", "Kevin"];
      let sorted = arr.sort((a,b) => {
       a.toLowerCase() > b.toLowerCase();
      })
      console.log(sorted);

      【讨论】:

        猜你喜欢
        • 2020-07-14
        • 2019-11-27
        • 1970-01-01
        • 2021-08-15
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        相关资源
        最近更新 更多