Intl API非常实用,遗憾的是在工作中,老是没想到有这么个东西。速速用起来吧。
Intl 对象是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比、数字格式化,和日期时间格式化。
兼容性:
Intl对象是从IE11+开始支持,其中有部分属性方法目前仅Chrome浏览器才支持,例如ListFormat。
控制台打印
Intl.Collator
Intl.Collator对象是排序器的构造函数,用于启用对语言敏感的字符串比较的对象。看起来在国际化上用的比较多
案例1 - 字符串数字排序
options有个可选参数是numeric
['100', '22', '3', '3d'].sort(new Intl.Collator(undefined, {numeric: true}).compare) // ["3", "3d", "22", "100"]
['100', '22', '3', 'd3d', 'D3d'].sort(new Intl.Collator(undefined, {numeric: true, caseFirst: 'upper'}).compare) // ["3", "22", "100", "D3d", "d3d"]
案例2 - 中文首字母拼音排序
['啊', '雷', '好', 'z'].sort() // ["z", "啊", "好", "雷"]
['啊', '雷', '好', 'z'].sort(new Intl.Collator('zh').compare) // ["啊", "好", "雷", "z"]
new Intl.Collator('zh').compare('b', 'a') // 1
new Intl.Collator('zh').compare('a', 'a') // 0
new Intl.Collator('zh').compare('a', 'b') // -1
new Intl.Collator('en').compare('b', 'a') // 1
new Intl.Collator('en').compare('a', 'a') // 0
new Intl.Collator('en').compare('a', 'b') // -1
Intl.DateTimeFormat
Intl.DateTimeFormat是根据语言来格式化日期和时间的对象的构造器。 指定语言日期展示 看起来下面几个是类似的
Date.prototype.toLocaleString()
Date.prototype.toLocaleDateString()
Date.prototype.toLocaleTimeString()
new Intl.DateTimeFormat('zh', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}).format(new Date()) // 2021/06/22 11:05:57
new Intl.DateTimeFormat('en-US', options).format(new Date()) // Tuesday, June 22, 2021
Intl.ListFormat
Intl.ListFormat 是一个语言相关的列表格式化构造器。
const vehicles = ['Motorcycle', 'Bus', 'Car'];
new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(vehicles) // "Motorcycle, Bus, and Car"
new Intl.ListFormat('zh', { style: 'long', type: 'conjunction' }).format(vehicles) // "Motorcycle、Bus和Car"
嗯,不知道哪里可以用。。。 new Intl.RelativeTimeFormat('zh').format(1, 'day')
Intl.NumberFormat
Intl.NumberFormat是对语言敏感的格式化数字类的构造器类
案例1 - 金钱处理
new Intl.NumberFormat().format(10000000) // 10,000,000 ⭐️
// 德语使用逗号作为小数点,使用.作为千位分隔符
new Intl.NumberFormat('de').format(10000000) // "10.000.000"
// 也可带上对应国际化的金钱单位。。。
new Intl.NumberFormat('zh', {
style: 'currency',
currency: "CNY"
}).format(12312312) // "¥12,312,312.00"
Intl.NumberFormat
多种语言规则的对象的构造函数。 没啥用 Intl.RelativeTimeFormat对象启用本地化的相对时间格式
new Intl.RelativeTimeFormat('zh').format(1, 'day') // "1天后"