Intl
对象是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比(Collator ),数字格式化(NumberFormat)等功能
collator这个单词意思是排序器。Intl.Collator对象是排序器的构造函数,可以支持对语言敏感的字符串比较。
语法:new Intl.Collator([locales[, options]])
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator
options有个可选参数是numeric,布尔属性,是否按照数值进行比较,默认是false
如果我们对字符串进行排序,会得到一个错误的结果,但是使用Intl.Collator对象就能得到正确的结果
['13', '2', '110', '100', '12'].sort();
// 结果是: ['100', '110', '12', '13', '2']
['13', '2', '110', '100', '12'].sort(new Intl.Collator(undefined, { numeric: true }).compare);
// 结果是:['2', '12', '13', '100', '110']
如果我们想对中文按照拼音排序,我们会遇到以下问题
const citys= ['上海','天津','广州','武汉','四川','重庆','北京']
citys.sort()
// 结果是:['上海', '北京', '四川', '天津', '广州', '武汉', '重庆']
如果我们使用Intl.Collator对象
citys.sort(new Intl.Collator('zh').compare);
// 结果是:['北京', '重庆', '广州', '上海', '四川', '天津', '武汉']
Intl.NumberFormat
可以根据不同语言环境对数值进行不同的格式化处理,他的参数和Number.toLocaleString()一样
语法:new Intl.NumberFormat([locales[, options]])
参考文档:[https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat]
常用的给金额加千分位
更多用法:https://zhuanlan.zhihu.com/p/356991916
new Intl.NumberFormat().format(1000.222);
// 结果是:'1,000.222'
如果我们想控制小数位数
new Intl.NumberFormat(undefined, {
minimumFractionDigits: 2, //最少几位小数
maximumFractionDigits: 2 //最多几位小数
}).format(1000.222)
// 结果是:'1,000.22'
如果想把数字转为百分比
new Intl.NumberFormat(undefined, { style: 'percent', maximumFractionDigits: 2 }).format(0.123222)
// 结果是:'12.32%'
如果不想要千分位
new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: false }).format(123456.000)
// 结果是:'123456.00'