JavaScript 国际化

原创
admin 4个月前 (08-19) 阅读数 19 #JavaScript
We are given an article about internationalization in JavaScript. The article covers the `Intl` object and its various functionalities for handling locale-specific operations. The article is structured as follows: 1. Overview of the `Intl` object and its use cases. 2. Locale information, including how to represent and use locales. 3. Figuring out the locale to use. 4. Understanding the return value of `Intl` methods. 5. Formatting data (dates, times, numbers, lists, relative times, durations). 6. Collation (string comparison and sorting). 7. Plural rules. 8. Segmentation (breaking text into segments). 9. Display names (getting localized names for various entities). We are to extract the main points and structure them in a way that captures the essence of the article. Key sections to cover: - Introduction to `Intl` - Locale representation and handling - Data formatting (with examples for dates, numbers, lists, etc.) - Collation - Plural rules - Segmentation - Display names We'll structure the response accordingly. ### JavaScript 国际化 (Internationalization) 指南 `Intl` 对象是 ECMAScript 国际化 API 的命名空间,提供了一系列区域设置和语言环境相关的数据与操作。以下是核心内容概览: --- #### **1. 概述** `Intl` 对象为不同场景提供专用对象: - **格式化数据**:`DateTimeFormat`、`DurationFormat`、`ListFormat`、`NumberFormat`、`RelativeTimeFormat` - **排序**:`Collator` - **复数规则**:`PluralRules` - **文本分段**:`Segmenter` - **显示名称**:`DisplayNames` - **区域信息**:`Locale` **基本用法**: ```javascript // 1. 创建格式化对象 const price = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }); // 2. 调用格式化方法 console.log(price.format(5.259)); // $5.26 ``` --- #### **2. 区域设置 (Locale)** 区域设置由语言、脚本、地区和变体组成(如 `en-US`)。可通过 `Intl.Locale` 对象操作: ```javascript const locale = new Intl.Locale("en-US"); console.log(locale.language); // "en" console.log(locale.region); // "US" ``` **扩展子标签**(如日历、数字系统): ```javascript // 方式1:语言标签扩展 const df1 = new Intl.DateTimeFormat("en-US-u-ca-hebrew"); // 方式2:选项对象 const df2 = new Intl.DateTimeFormat("en-US", { calendar: "hebrew" }); ``` --- #### **3. 数据格式化** ##### **日期时间格式化 (`DateTimeFormat`)** ```javascript const df = new Intl.DateTimeFormat("en-US", { calendar: "hebrew", // 使用希伯来历 timeZone: "Asia/Tokyo", dateStyle: "full", // 完整日期格式 timeStyle: "full" }); console.log(df.format(new Date())); // "星期六, 2023年1月1日 上午9:00:00 日本标准时间" ``` ##### **数字格式化 (`NumberFormat`)** ```javascript const nf = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", notation: "compact" // 紧凑表示法 }); console.log(nf.format(1234567)); // "$1.2M" ``` ##### **列表格式化 (`ListFormat`)** ```javascript const fruits = ["apple", "banana", "cherry"]; const lf = new Intl.ListFormat("en-US", { style: "long", type: "conjunction" }); console.log(lf.format(fruits)); // "apple, banana, and cherry" ``` ##### **相对时间格式化 (`RelativeTimeFormat`)** ```javascript const rtf = new Intl.RelativeTimeFormat("en-US", { numeric: "auto" }); console.log(rtf.format(1, "day")); // "tomorrow" console.log(rtf.format(-1, "hour")); // "1 hour ago" ``` --- #### **4. 排序 (Collation)** 用于字符串比较和排序,支持多种排序规则: ```javascript const names = ["Hochberg", "Hönigswald", "Holzman"]; // 电话簿排序(按发音) const phonebookSort = new Intl.Collator("de-DE-u-co-phonebk"); console.log(names.sort(phonebookSort.compare)); // ["Hochberg", "Hönigswald", "Holzman"] // 字典排序(忽略变音符号) const dictSort = new Intl.Collator("de-DE-u-co-dict"); console.log(names.sort(dictSort.compare).join(", ")); // "Hochberg, Holzman, Hönigswald" ``` --- #### **5. 复数规则 (PluralRules)** 根据数字选择正确的复数形式: ```javascript const pr = new Intl.PluralRules("en-US"); const suffixes = { one: "st", two: "nd", few: "rd", other: "th" }; console.log(`The ${42}${suffixes[pr.select(42)]} president`); // "The 42nd president" ``` --- #### **6. 文本分段 (Segmenter)** 将文本拆分为有意义的单元(字符、单词、句子): ```javascript // 字符级分段(处理 Emoji) const segmenter = new Intl.Segmenter("en-US", { granularity: "grapheme" }); console.log([...segmenter.segment("🇺🇸🇨🇳")].map(s => s.segment)); // ["🇺🇸", "🇨🇳"] // 单词级分段 const wordSegmenter = new Intl.Segmenter("zh-Hans", { granularity: "word" }); console.log([...wordSegmenter.segment("我是作者")].map(s => s.segment)); // ["我是", "作者"] ``` --- #### **7. 显示名称 (DisplayNames)** 获取区域设置相关的本地化名称: ```javascript const dn = new Intl.DisplayNames("zh-CN", { type: "language" }); console.log(dn.of("en-US")); // "美国英语" console.log(dn.of("EUR")); // "欧元" ``` --- #### **8. 最佳实践** 1. **选择区域设置**: - 使用 `navigator.languages` 获取用户偏好 - 或通过后端/前端状态管理(如 `userSettings.locale`) 2. **避免硬编码输出**: ```javascript // 错误:直接比较字符串 expect(result).toBe("$5.26"); // 正确:快照测试 expect(result).toMatchSnapshot(); ``` 3. **性能优化**: - 重复格式化时复用格式化对象 - 使用 `toLocaleString()` 适合简单场景 --- #### **总结** `Intl` API 通过模块化设计(如 `NumberFormat`、`Collator`)解决了国际化中的核心问题: - **数据格式化**:日期、数字、列表等 - **文本处理**:排序、复数、分段 - **用户界面**:显示名称、区域设置选择 正确使用 `Intl` 可确保应用在不同语言和地区中提供一致、自然的用户体验。
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。

作者文章
热门
最新文章
标签列表