簡體   English   中英

為什么 Intl.Collator 對負數進行降序排序?

[英]Why does Intl.Collator sort negative numbers in descending order?

我遇到了這個用例,我對此感到困惑:

 const naturalCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); const comparator = (a, b) => naturalCollator.compare(a, b); const numbers = [-1, 0, 1, 10, NaN, 2, -0.001, NaN, 0, -1, -Infinity, NaN, 5, -10, Infinity, 0]; console.log(numbers.sort(comparator));

結果數組以降序排列負數,而以升序排列正數。 例如:

[-3, 1, -2, 2].sort(comparator)
// [-2, -3, 1, 2]

由於Intl.Collator是一個“語言敏感的字符串比較”,它是否簡單地忽略符號並且只將每個數字評估為正數?

編輯

另一個不一致是這個:

["b1", "a-1", "b-1", "a+1", "a1"].sort(comparator);
// ['a-1', 'a+1', 'a1', 'b-1', 'b1']

其中'a' < 'b'所以順序沒問題,但是'-' > '+'那么為什么"a-1""a+1"之前?

換句話說,無論字符代碼如何,負號都被認為小於正號,但是"-1"被認為小於"-2" ,忽略符號。

默認的字符串排序算法對正在比較的字符串中的每個代碼單元使用 unicode 個值。 這稱為“詞典排序”。

當您設置整理器選項時,您正在定義對此行為的特定覆蓋(您可以將它們視為比字典排序更高優先級的規則)。

這是相關規范部分的鏈接: https://tc39.es/ecma402/#sec-collator-comparestrings

比較數字值時(如您的示例),第一步是將數字強制轉換為字符串,然后再用於內部排序 function。

使用numeric選項時,效果僅適用於歸類為數字的代碼單元。

對於字符串化的負值,連字符被評估為非數字字符。 然后將連續的數字序列評估為類似數字的組。

在對以連字符和數字開頭的其他字符串進行排序時,您可以看到這樣做的效果:

 const opts = { numeric: true, sensitivity: 'base' }; const naturalCollator = new Intl.Collator(undefined, opts); const values = [-3, 1, -2, 2, '-foo', '-bar', 'foo', 'bar']; console.log(values.sort(naturalCollator.compare)); //=> [-2, -3, "-bar", "-foo", 1, 2, "bar", "foo"]


numeric選項有用的另一個例子:考慮一系列帶有數字子字符串的文件名,用於分組排序:

 const opts = { numeric: true, sensitivity: 'base' }; const naturalCollator = new Intl.Collator(undefined, opts); const fileNames = [ 'IMG_1.jpg', 'IMG_2.jpg', 'IMG_3.jpg', //... 'IMG_100.jpg', 'IMG_101.jpg', 'IMG_102.jpg', //... 'IMG_200.jpg', 'IMG_201.jpg', 'IMG_202.jpg', // etc... ]; fileNames.sort(); console.log(fileNames); // //=> ["IMG_1.jpg", "IMG_100.jpg", "IMG_101.jpg", "IMG_102.jpg", "IMG_2.jpg", "IMG_200.jpg", "IMG_201.jpg", "IMG_202.jpg", "IMG_3.jpg"] fileNames.sort(naturalCollator.compare); console.log(fileNames); // //=> ["IMG_1.jpg", "IMG_2.jpg", "IMG_3.jpg", "IMG_100.jpg", "IMG_101.jpg", "IMG_102.jpg", "IMG_200.jpg", "IMG_201.jpg", "IMG_202.jpg"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM