JavaScript TypedArray toString() 方法返回当前类型化数组及其元素的字符串表示形式。当类型化数组要表示为文本值时,例如,当类型化数组与字符串连接时,JavaScript 会自动调用 toString 方法。
注意 − 它将类型化数组隐式转换为字符串,这意味着类型化数组由 JavaScript 引擎自动更改。
语法
以下是 JavaScript TypedArray toString() 方法的语法 -
toString()
参数
它不接受任何参数。
返回值
此方法返回类型化数组元素的字符串表示形式。
示例 1
在下面的示例中,我们使用 JavaScript Typedarray toString() 方法来检索类型化数组的字符串表示形式:[1, 2, 3, 4, 5]。
<html>
<head>
<title>JavaScript TypedArray toString() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5]);
document.write("Typed array: ", T_array);
//using toString() method
let str = T_array.toString();
document.write("<br>String representating typed array: ", str);
document.write("<br>Type of str(after converting to a string): ", typeof(str));
</script>
</body>
</html>
输出
上面的程序返回一个表示类型化数组的字符串 -
Typed array: 1,2,3,4,5
String representating typed array: 1,2,3,4,5
Type of str(after converting to a string): string
String representating typed array: 1,2,3,4,5
Type of str(after converting to a string): string
示例 2
下面是使用 JavaScript TypedArray toString() 方法将类型化数组 [10, 20, 30, 40, 50, 60, 70, 80] 显式转换为字符串的另一个示例。此外,我们将查看一个隐式方法来获得相同的结果。
<html>
<head>
<title>JavaScript TypedArray toString() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50, 60, 70, 80]);
document.write("Typed array: ", T_array);
//using toString() method
//explicit conversion
let str = T_array.toString();
document.write("<br>String representating typed array(explicit): ", str);
document.write("<br>Type of str(after converting to a string): ", typeof(str));
//implicit conversion
let new_str = `${T_array}`;
document.write("<br>String representating typed array(implicit ): ", new_str);
document.write("<br>Type of str(after converting to a string): ", typeof(new_str));
</script>
</body>
</html>
输出
执行上述程序后,它将返回一个字符串表示类型化数组:
Typed array: 10,20,30,40,50,60,70,80
String representating typed array(explicit): 10,20,30,40,50,60,70,80
Type of str(after converting to a string): string
String representating typed array(implicit ): 10,20,30,40,50,60,70,80
Type of str(after converting to a string): string
String representating typed array(explicit): 10,20,30,40,50,60,70,80
Type of str(after converting to a string): string
String representating typed array(implicit ): 10,20,30,40,50,60,70,80
Type of str(after converting to a string): string