代码之家  ›  专栏  ›  技术社区  ›  user1063287

如何使用localecompare对包含负值的数字数组进行排序?

  •  1
  • user1063287  · 技术社区  · 5 年前

    我正在尝试将数组从最低值排序到最高值。

    下面的示例显示它已经按这种方式排序

    var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"];
    

    但是,当我这样做时:

    var array = ["-394", "-275", "-156", "-37", "82", "201", "320", "439", "558", "677", "796"];
    array.sort(function(a, b) {
      return a.localeCompare(b, undefined, {
        numeric: true
      })
    });
    console.log(array);

    这将被返回(我不确定发生了什么排序):

    ["-37", "-156", "-275", "-394", "82", "201", "320", "439", "558", "677", "796"]
    

    我看过:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

    但它似乎没有特别提到处理负数的问题。

    对包含负值的数字数组进行排序的正确方法是什么?

    2 回复  |  直到 5 年前
        1
  •  4
  •   CertainPerformance    5 年前

    因为数组项可以直接强制为数字,为什么不改为这样做呢?

    var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"];
    array.sort(function(a,b) { return a - b } );
    console.log(array);

    这个 a - b 它使用减法运算符,将强制两边的表达式为数字。

    很遗憾,数字排序规则没有考虑到 - 标志。当前代码将导致排序器排序 - 数字前面的数字没有 - 在他们面前(因为 - 在数字之前,字面上)。

    console.log('-'.charCodeAt());
    console.log('0'.charCodeAt());

    所以有了

      "-37",
      "-156",
      "-275",
      "-394",
    

    37在156之前,275之前,394之前。(同样的事情也发生在正数上,它们都是在后面出现的)。

        2
  •  0
  •   Jack Bashford    5 年前

    只是使用 sort -所有项目都可以隐式转换为数字。

    var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"];
    const res = array.sort((a, b) => a - b);
    console.log(res);
    .as-console-wrapper { max-height: 100% !important; top: auto; }