JavaScript - TypedArray join() 方法



JavaScript TypedArray 的join()方法用于创建并返回一个字符串,该字符串通过连接 TypedArray 元素并用逗号(默认分隔符)或指定的分隔符字符串分隔它们来创建。如果当前 TypedArray 只包含一个元素,则该元素将按原样返回,不使用分隔符。

如果当前 TypedArray 为空(或 arr.length 为0),则返回空字符串。

语法

以下是 JavaScript TypedArray join() 方法的语法:

join(separator)

参数

此方法接受一个名为“separator”的参数,如下所述:

  • separator (可选) − 用于连接 TypedArray 元素时分隔每个元素的字符串。

返回值

此方法返回一个包含所有 TypedArray 元素的连接字符串。

示例

示例 1

如果省略separator参数,则它会将 TypedArray 元素连接起来,并用逗号分隔。

在下面的程序中,我们使用 JavaScript TypedArray 的join()方法来连接这个 TypedArray 元素 [1, 2, 3, 4, 5, 6, 7, 8],并用逗号分隔。

<html>
<head>
   <title>JavaScript TypedArray join() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint16Array([1, 2, 3, 4, 5, 6, 7, 8]);
      document.write("Typed array: ", T_array);
      
      //using join() method
      let new_str = "";
      new_str = T_array.join();
      document.write("<br>New concatenated string: ", new_str);
   </script>
</body>
</html>

输出

以上代码返回用逗号分隔的连接字符串:

Typed array: 1,2,3,4,5,6,7,8
New concatenated string: 1,2,3,4,5,6,7,8

示例 2

如果我们将separator参数的值设置为"−",它将连接 TypedArray 元素,并用指定的分隔符分隔它们。

以下是 JavaScript TypedArray join() 方法的另一个示例。我们使用此方法来连接这个 TypedArray 元素 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],并用指定的分隔符字符串"−"分隔它们。

<html>
<head>
   <title>JavaScript TypedArray join() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint16Array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);
      document.write("Typed array: ", T_array);
      const separator_str = "-";
      document.write("<br>Separator: ", separator_str);
      
      //using join() method
      let new_str = "";
      new_str = T_array.join(separator_str);
      document.write("<br>New concatenated string: ", new_str);
   </script>
</body>
</html>

输出

执行上述程序后,它将返回一个用“−”分隔的新连接字符串。

Typed array: 10,20,30,40,50,60,70,80,90,100
Separator: -
New concatenated string: 10-20-30-40-50-60-70-80-90-100

示例 3

如果当前 TypedArray 只有一个元素"new Uint16Array([100])",则返回相同的元素,不使用分隔符。

<html>
<head>
   <title>JavaScript TypedArray join() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint16Array([100]);
      document.write("Typed array: ", T_array);
      const separator_str = "-#-";
      document.write("<br>Separator: ", separator_str);
      
      //using join() method
      let new_str = "";
      new_str = T_array.join(separator_str);
      document.write("<br>New concatenated string: ", new_str);
   </script>
</body>
</html>

输出

执行上述程序后,它将返回连接字符串,不使用分隔符。

Typed array: 100
Separator: -#-
New concatenated string: 100
广告
© . All rights reserved.