JavaScript - 数组 toLocaleString() 方法
JavaScript Array.toLocaleString() 方法用于根据系统区域设置将数组转换为本地化的字符串表示形式。它会根据指定的区域设置对数字、日期和其他数据类型进行本地化。默认情况下,它使用系统区域设置,但您也可以指定其他区域设置作为参数。
语法
以下是 JavaScript Array toLocaleString() 方法的语法 -
toLocaleString(locales, options)
参数
此方法接受两个可选参数。下文将对此进行描述 -
- locales - 它是一个带有 BCP 47 语言标签的字符串,用于指定语言和格式选项。
- options - 一个对象用作选项,用于更改样式、货币、最小和最大小数位数等。
返回值
此方法返回当前数组元素的字符串表示形式。
示例
示例 1
在下面的示例中,我们对数字数组调用 JavaScript Array.toLocaleString() 方法。
<html>
<body>
<script>
const numbers = [1000000, 2000000, 3000000];
document.write(numbers.toLocaleString());
</script>
</body>
</html>
返回数组的字符串表示形式,其中每个数字均根据特定语言环境的规则进行格式化。
输出
1,000,000,2,000,000,3,000,000
示例 2
在此示例中,我们对日期数组调用 toLocaleString() 方法。
<html>
<body>
<script>
const dates = [new Date('2023-01-01'), new Date('2023-02-01'), new Date('2023-03-01')];
document.write(dates.toLocaleString());
</script>
</body>
</html>
返回数组的字符串表示形式,其中每个日期均根据特定于语言环境的规则进行格式化。
输出
1/1/2023, 5:30:00 AM,2/1/2023, 5:30:00 AM,3/1/2023, 5:30:00 AM
示例 3
在此示例中,我们对货币值数组调用 Array 的 toLocaleString() 方法。
<html>
<body>
<script>
const currency = [1000, 2000, 3000];
document.write(currency.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
</script>
</body>
</html>
它返回数组的字符串表示形式,其中每个数字都格式化为美元的货币值。
输出
$1,000.00,$2,000.00,$3,000.00

