JavaScript - Array.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
广告
© . All rights reserved.