Array.prototype.toLocaleString()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

toLocaleString() 方法是 Array 实例的一个方法,它返回一个表示数组元素的字符串。元素使用它们的 toLocaleString 方法转换为字符串,这些字符串由一个特定于区域设置的字符串(例如逗号 ",")分隔。

试一试

const array = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")];
const localeString = array.toLocaleString("en", { timeZone: "UTC" });

console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary

语法

js
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

参数

locales 可选

一个带有 BCP 47 语言标签的字符串,或者此类字符串的数组。关于 locales 参数的一般形式和解释,请参阅 Intl 主页上的参数说明

options 可选

一个带有配置属性的对象。这里可以传递的内容取决于正在转换的元素。例如,对于数字,请参阅 Number.prototype.toLocaleString()

返回值

一个表示数组元素的字符串。

描述

Array.prototype.toLocaleString 方法会遍历其内容,使用提供的 localesoptions 参数调用每个元素的 toLocaleString 方法,并将它们连接起来,分隔符由实现定义(例如逗号 ",")。

注意: localesoptions 参数不控制数组元素之间的分隔符;它们只是被传递给每个元素的 toLocaleString() 方法。实际的分隔符(通常是逗号)仅取决于主机当前的区域设置。如果您期望本地化的列表格式,请考虑使用 Intl.ListFormat

如果元素是 undefinednull,它将被转换为一个空字符串,而不是字符串 "null""undefined"

当用于 稀疏数组时,toLocaleString() 方法会将空槽视为具有 undefined 值进行迭代。

toLocaleString() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。

示例

使用区域设置和选项

数组的元素使用它们的 toLocaleString 方法转换为字符串。例如,这个片段会隐式调用 Number.prototype.toLocaleString() 方法来显示 prices 数组中字符串和数字的货币。

js
const prices = ["¥7", 500, 8123, 12];
prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });

// "¥7,¥500,¥8,123,¥12"

列表分隔符

列表分隔符不受 locales 参数的影响。要配置它,请改用 Intl.ListFormat

js
const nums = [8888, 9999];
console.log(nums.toLocaleString("zh")); // "8,888,9,999"

const formatter = new Intl.ListFormat("zh", {
  type: "conjunction",
  style: "narrow",
});
console.log(formatter.format(nums.map((x) => x.toLocaleString("zh"))));
// "8,888、9,999"

在稀疏数组上使用 toLocaleString()

toLocaleString() 将空槽视为与 undefined 相同,并产生一个额外的分隔符。

js
console.log([1, , 3].toLocaleString()); // '1,,3'

在非数组对象上调用 toLocaleString()

toLocaleString() 方法会读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

js
const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
  3: 4, // ignored by toLocaleString() since length is 3
};
console.log(Array.prototype.toLocaleString.call(arrayLike));
// 1,2,3

规范

规范
ECMAScript® 2026 语言规范
# sec-array.prototype.tolocalestring
ECMAScript® 2026 国际化 API 规范
# sup-array.prototype.tolocalestring

浏览器兼容性

另见