【问题标题】:localCompare for Integers整数的 localeCompare
【发布时间】:2013-08-29 10:49:57
【问题描述】:

我正在使用 localCompare 来比较一些字符串,这些字符串是数字。我希望订单是数字的。我该怎么做?

排序功能:

requestAmountEl.find('optgroup').each(function(){
    var $this = jQuery(this);

    options = $this.children('option');
    options.detach().sort(function(a,b) {
        return b.value.localeCompare(a.value);
    }).appendTo($this);
});

结果:

<optgroup label="6 Months">
    <option value="2000">$2,000</option>
    <option value="11000">$11,000</option>
    <option value="10000">$10,000</option>
    <option value="1000">$1,000</option>
</optgroup>

现在它会排序 2000、10000、11000、1000。

【问题讨论】:

    标签: javascript numbers integer compare


    【解决方案1】:

    String.localeCompare 有你需要的东西。传入数字选项,它会将您的字符串视为数字:

    ['2000', '11000', '10000', '1000'].sort(
      (a, b) => a.localeCompare(b, undefined, {'numeric': true})
    );
    

    ...结果:

    ["1000", "2000", "10000", "11000"]
    

    【讨论】:

      【解决方案2】:

      解决方案:

      requestAmountEl.find('optgroup').each(function(){
          var $this = jQuery(this);
      
          options = $this.children('option');
          options.detach().sort(function(a,b) {
              if (parseInt(b.value) > parseInt(a.value)) return 1;
              else if (parseInt(b.value) < parseInt(a.value)) return -1;
              else return 0;
          }).appendTo($this);
      });
      

      【讨论】:

        猜你喜欢
        • 2020-05-14
        • 1970-01-01
        • 2016-10-18
        • 2019-03-27
        • 1970-01-01
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        相关资源
        最近更新 更多