整数的本地比较

2 javascript integer compare numbers

我正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)

结果:

<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>
Run Code Online (Sandbox Code Playgroud)

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

pom*_*omo 8

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

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

... 结果是:

["1000", "2000", "10000", "11000"]
Run Code Online (Sandbox Code Playgroud)