JavaScript - TypedArray toString() 方法



JavaScript TypedArray 的 toString() 方法返回当前 TypedArray 及其元素的字符串表示形式。当 TypedArray 要表示为文本值时(例如,当 TypedArray 与字符串连接时),JavaScript 会自动调用 toString 方法。

注意 - 它将 TypedArray 隐式转换为字符串,这意味着 TypedArray 会被 JavaScript 引擎自动更改。

语法

以下是 JavaScript TypedArray toString() 方法的语法 -

toString()

参数

  • 它不接受任何参数。

返回值

此方法返回 TypedArray 元素的字符串表示形式。

示例

示例 1

在以下示例中,我们使用 JavaScript Typedarray 的 toString() 方法来检索 TypedArray 的字符串表示形式:[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>

输出

以上程序返回一个表示 TypedArray 的字符串 -

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

示例 2

以下是使用 JavaScript TypedArray 的 toString() 方法将 TypedArray [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>

输出

执行上述程序后,它将返回 TypedArray 的字符串表示形式

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
广告

© . All rights reserved.