推荐答案
// www.javascriptcn.com code example
// 使用 Intl.DateTimeFormat 格式化日期
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit',
weekday: 'long'
});
console.log(formatter.format(date)); // 输出: "Thursday, October 05, 2023"
// 使用 Intl.NumberFormat 格式化数字
const number = 123456.789;
const numberFormatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
});
console.log(numberFormatter.format(number)); // 输出: "123.456,79 €"
// 使用 Intl.Collator 进行字符串排序
const collator = new Intl.Collator('fr');
const words = ['résumé', 'resume', 'café', 'cafe'];
console.log(words.sort(collator.compare)); // 输出: ["cafe", "café", "resume", "résumé"]本题详细解读
Intl 对象概述
Intl 是 JavaScript 中的一个内置对象,用于国际化(i18n)和本地化(l10n)操作。它提供了多种工具来处理日期、时间、数字、货币、字符串排序等与语言和地区相关的操作。
Intl.DateTimeFormat
Intl.DateTimeFormat 用于根据指定的语言和地区格式化日期和时间。你可以通过传递不同的选项来控制输出的格式,例如年份、月份、日期、星期等。
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit',
weekday: 'long'
});
console.log(formatter.format(date)); // 输出: "Thursday, October 05, 2023"Intl.NumberFormat
Intl.NumberFormat 用于格式化数字,包括货币、百分比、小数位数等。你可以指定语言和地区,以及格式化样式(如货币、百分比等)。
const number = 123456.789;
const numberFormatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
});
console.log(numberFormatter.format(number)); // 输出: "123.456,79 €"Intl.Collator
Intl.Collator 用于字符串的排序和比较。它可以根据指定的语言和地区规则对字符串进行排序,支持大小写敏感、重音符号敏感等选项。
const collator = new Intl.Collator('fr');
const words = ['résumé', 'resume', 'café', 'cafe'];
console.log(words.sort(collator.compare)); // 输出: ["cafe", "café", "resume", "résumé"]其他 Intl 对象
除了上述常用的 Intl.DateTimeFormat、Intl.NumberFormat 和 Intl.Collator 外,Intl 对象还提供了其他一些功能,如 Intl.ListFormat(用于格式化列表)、Intl.PluralRules(用于处理复数形式)等。
总结
Intl 对象为 JavaScript 提供了强大的国际化支持,使得开发者可以轻松地处理不同语言和地区的日期、时间、数字、货币、字符串排序等问题。通过合理使用 Intl 对象,可以显著提升应用程序的国际化能力。