JavaScript - TypedArray toLocaleString() 方法
JavaScript TypedArray toLocaleString() 方法返回当前类型数组元素的字符串表示形式。使用此方法将类型化数组元素转换为字符串,并使用指定的特定于语言环境分隔符(例如逗号(",")、符号 ($, ₹) 等)分隔这些字符串。
指定的语言环境参数为 BCP(当前最佳实践)。47 种语言标签是区域化语言表示的标准。
语法
以下是 JavaScript TypedArray toLocaleString() 方法的语法 -
toLocaleString(locales, options)
参数
此方法接受两个名为"locales"和"options"的参数,如下所述 -
locales - 它是一个带有 BCP 47 语言标签的字符串,该标签指定语言和格式选项。
options − 一个对象用作选项,用于更改样式、货币、最小和最大小数位数等。
返回值
此方法返回当前类型数组元素的字符串表示形式。
示例
示例 1
如果同时省略 locales 和 options 参数,则会根据您的系统语言环境将当前类型数组 [1000, 205, 5993, 4032] 的元素转换为字符串,并使用逗号 (',') 分隔字符串。
<html>
<head>
<title>JavaScript TypedArray toLocaleString() Method</title>
</head>
<body>
<script>
const T_array = new Int16Array([1000, 205, 5993, 4032]);
document.write("Typed array: ", T_array);
//使用 toLocaleString() 方法
let str = T_array.toLocaleString();
document.write("<br>The string representing typed array elements: ", str);
</script>
</body>
</html>
输出
上述程序返回一个表示类型化数组元素的字符串 -
Typed array: 1000,205,5993,4032 The string representing typed array elements: 1,000,205,5,993,4,032
示例 2
如果我们仅将 "locale" 参数传递给此方法,它会根据指定的语言环境将类型化数组元素转换为字符串。
以下是 JavaScript TypedArray toLocaleString() 方法的另一个示例。我们使用此方法根据指定的语言环境 "de-DE" 检索此类型数组元素的字符串表示形式 [4023, 6123, 30, 146]。
<html>
<head>
<title>JavaScript TypedArray toLocaleString() Method</title>
</head>
<body>
<script>
const T_array = new Int16Array([4023, 6123, 30, 146]);
document.write("Typed array: ", T_array);
const locale = "de-DE";
document.write("<br>The locale: ", locale);
//使用 toLocaleString() 方法
let str = T_array.toLocaleString(locale);
document.write("<br>The string representing typed array elements: ", str);
</script>
</body>
</html>
输出
执行上述程序后,将返回一个表示类型化数组元素的字符串,如下所示:-
Typed array: 4023,6123,30,146 The locale: de-DE The string representing typed array elements: 4.023,6.123,30,146
示例 3
如果我们将 locale 和 options 参数同时传递给此方法,它将根据指定的语言环境和选项(配置货币符号等属性)将类型化数组元素转换为字符串。
在下面的示例中,我们使用 JavaScript TypedArray toLocaleString() 方法检索此类型化数组元素的字符串表示形式 [5034, 6946, 234, 1003] 使用指定的国家/地区语言环境"en-In"和货币符号"₹"。
<html>
<head>
<title>JavaScript TypedArray toLocaleString() Method</title>
</head>
<body>
<script>
const T_array = new Int16Array([5034, 6946, 234, 1003]);
document.write("Typed array: ", T_array);
const locale = "en-IN";
const options = {style: "currency", currency: "INR"};
document.write("<br>The locale: ", locale);
document.write("<br>The options: ", options.style,", ",options.currency);
//使用 toLocaleString() 方法
let str = T_array.toLocaleString(locale, options);
document.write("<br>The string representing typed array elements: ", str);
</script>
</body>
</html>
输出
上述程序执行后,将显示如下所示的输出 -
Typed array: 5034,6946,234,1003 The locale: en-IN The options: currency, INR The string representing typed array elements: ₹5,034.00,₹6,946.00,₹234.00,₹1,003.00

