大网数据广告活动
Web 标准与前端开发

Array.prototype.toLocaleString()

· 52CE 我爱测

**`toLocaleString()`** 方法返回一个字符串,表示数组中的所有元素。每个元素通过调用它们自己的 `toLocaleString` 方法转换为字符串,并且使用特定于语言环境的字符串(例如逗号“,”)分隔开。

toLocaleString() 方法返回一个字符串,表示数组中的所有元素。每个元素通过调用它们自己的 toLocaleString 方法转换为字符串,并且使用特定于语言环境的字符串(例如逗号“,”)分隔开。

JavaScript Demo: Array.toLocaleString()

const array1 = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")];
const localeString = array1.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

语法

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

参数

  • locales
    • : 带有 BCP 47 语言标签的字符串,或者此类字符串的数组。对于 locales 参数的一般形式和说明,可以参见 Intl 主页面的参数说明。
  • options
    • : 一个具有配置属性的对象。对于数字,请参见 Number.prototype.toLocaleString();对于日期,请参见 Date.prototype.toLocaleString()。

返回值

一个字符串,表示数组中的所有元素。

描述

Array.prototype.toLocaleString 方法遍历数组内容,并使用提供的 locales 和 options 参数调用每个元素的 toLocaleString 方法,通过由实现定义的分隔符(例如逗号“,”)将转换后的字符串拼接起来。请注意,该方法本身不会使用这两个参数——它只是将其传递给每个元素的 toLocaleString()。分隔符的选择取决于主机当前的语言环境,而不是 locales 参数。

如果一个元素是 undefined、null,它会被转换为空字符串,而不是 "null" 或者 "undefined"。

当用于稀疏数组时,toLocaleString() 方法迭代时会把空槽当作 undefined 一样处理它。

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

示例

使用 locales 和 options

数组元素通过使用它们的 toLocaleString 方法转换为字符串。

  • Object:Object.prototype.toLocaleString()
  • Number:Number.prototype.toLocaleString()
  • Date:Date.prototype.toLocaleString()

始终显示 prices 数组中字符串和数字的货币符号:

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

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

更多示例请参见 Intl.NumberFormat 和 Intl.DateTimeFormat 页面。

在稀疏数组中使用 toLocaleString()

toLocaleString() 将空槽视为 undefined ,并生成一个额外的分隔符:

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

在非数组对象中使用 toLocaleString()

toLocaleString() 方法读取 this 的 length 属性,然后访问每个整数索引。

const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
};
console.log(Array.prototype.toLocaleString.call(arrayLike));
// 1,2,3

规范

浏览器兼容性

参见

  • 索引集合
  • Array
  • Array.prototype.toString()
  • TypedArray.prototype.toLocaleString()
  • Intl
  • Intl.ListFormat
  • Object.prototype.toLocaleString()
  • Number.prototype.toLocaleString()
  • Date.prototype.toLocaleString()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。