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