let list = [1, 2, 3, 10, 11, 12, 20, 21, 22, 100, 102, 103, 200, 201, 202, 130, 220];
// numeric: 是否按照數值進行比較
let collator = Intl.Collator(undefined, { numeric: true });
list.sort(); // [ 1, 10, 100, 102, 103, 11, 12, 130, 2, 20, 200, 201, 202, 21, 22, 220, 3 ]
list.sort(collator.compare); // [ 1, 2, 3, 10, 11, 12, 20, 21, 22, 100, 102, 103, 130, 200, 201, 202, 220 ]
let namelist = [
'陳坤',
'鄧超',
'杜淳',
'馮紹峰',
'韓庚',
'胡歌',
'黃曉明',
'賈乃亮',
'李晨',
'李易峰',
'鹿晗',
'井柏然',
'劉燁',
'陸毅',
'孫紅雷'
];
namelist.sort(); // [ '井柏然', '馮紹峰', '劉燁', '孫紅雷', '李易峰', '李晨', '杜淳', '胡歌', '賈乃亮', '鄧超', '陸毅', '陳坤', '韓庚', '鹿晗', '黃曉明' ]
namelist.sort(new Intl.Collator('zh').compare); // [ '陳坤', '鄧超', '杜淳', '馮紹峰', '韓庚', '胡歌', '黃曉明', '賈乃亮', '井柏然', '李晨', '李易峰', '劉燁', '陸毅', '鹿晗', '孫紅雷' ]
const format = new Intl.DateTimeFormat('zh-Hans', {
year: 'numeric',
month: '2-digit',
// weekday: 'long',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
// 創建一個新的 DateTimeFormat 實例
const format2 = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
// 格式化當前日期和時間
format.format(new Date()); // '2024/05/25 17:06:02'
format2.format(new Date()); // '2024年5月25日 17:06:24'
// 讓對語言敏感的列表進行格式化
var vehicles = ['Motorcycle', 'Bus', 'Car'];
var formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(vehicles)); // 'Motorcycle, Bus, and Car'
Intl.NumberFormat(undefined, {
minimumFractionDigits: 10
}).format(123456789056.123); // '123,456,789,056.1230000000'
new Intl.NumberFormat('zh-Hans', {
style: 'currency',
currency: 'CNY',
currencyDisplay: 'name'
}).format(12345.6789); // '12,345.68人民幣'
'星期' + new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(new Date().getDay()); // '星期六'
new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec', {
style: 'currency',
currency: 'CNY',
currencyDisplay: 'name',
useGrouping: false
}).format(1234); // '一二三四.〇〇人民幣'
new Intl.PluralRules('ar-EG').select(0);
// → 'zero'
new Intl.PluralRules('ar-EG').select(1);
// → 'one'
new Intl.PluralRules('ar-EG').select(2);
// → 'two'
new Intl.PluralRules('ar-EG').select(6);
// → 'few'
new Intl.PluralRules('ar-EG').select(18);
// → 'many'
let rtf = new Intl.RelativeTimeFormat('zh', {
numeric: 'auto'
});
// -1表示前一天
rtf.format(-1, 'day'); // '昨天'
rtf.format(1, 'day'); // '明天'
rtf.format(-365, 'day'); // '365天前'
Intl.getCanonicalLocales('zh-hans');
// 結果是:["zh-Hans"]
Intl.getCanonicalLocales('zh');
// 結果是:["zh"]
Intl.getCanonicalLocales('zh-cmn-Hans-CN');
// 結果是:["cmn-Hans-CN"]
Intl.getCanonicalLocales('zh-cn');
// 結果是:["zh-CN"]
Intl.getCanonicalLocales('yue-hk');
// 結果是:["yue-HK"]
Intl.getCanonicalLocales('zh-some');
// 結果是:["zh-Some"]