使用 gulp-inject 注入到頁面之前,需要對文件進行排序。在使用排序方法時發(fā)現(xiàn) String.prototype.localeCompare 的這個方法在 Mac 和 Windows 環(huán)境結果不同。
使用 localeCompare 測試
[‘A', 'a', 'B', 'b'].sort(function(a, b) { return a.localeCompare(b); })
mac
[ 'A', 'B', 'a', 'b' ]
windows
[ ‘a(chǎn)', 'A', 'b', 'B' ]
不使用 localeCompare 測試
[‘A’, ‘a(chǎn)’, ‘B’, 'b'].sort();
mac
[ 'A', 'B', 'a', 'b' ]
windows
[ 'A', 'B', 'a', 'b' ]
根據(jù) String.prototype.localeCompare() - JavaScript | MDN 說明,localeCompare 方法是和操作系統(tǒng) locale 值相關。
我們可以使用 localeCompare 函數(shù)的第二個參數(shù) locale 的 BCP 47 language 擴展 kf 參數(shù)來確定大小寫優(yōu)先順序。
但首先需要先了解什么是 BCP 47 language tag ,啊,好麻煩...
也可以自定義檢測字符大小寫的函數(shù)作為 localCompare 的比較器
function caseInsensitiveComparator(valueA, valueB) {
var valueALowerCase = valueA.toLowerCase();
var valueBLowerCase = valueB.toLowerCase();
if (valueALowerCase < valueBLowerCase) {
return -1;
} else if (valueALowerCase > valueBLowerCase) {
return 1;
} else { //valueALowerCase === valueBLowerCase
if (valueA < valueB) {
return -1;
} else if (valueA > valueB) {
return 1;
} else {
return 0;
}
}
}
參考:
How to perform case insensitive sorting in Javascript? - Stack Overflow