Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน TypedArray.join() ใน JavaScript


เมธอด join() ของออบเจ็กต์ TypedArray ใช้สำหรับรวมองค์ประกอบทั้งหมดใน typed array ให้เป็นสตริงเดียวและคืนค่ากลับ โดยคุณสามารถระบุตัวคั่น (separator) เพื่อแยกแต่ละองค์ประกอบได้

รูปแบบไวยากรณ์ (Syntax)

typedArray.join(separator)

พารามิเตอร์:

  • separator (ไม่บังคับ): สตริงที่ใช้คั่นระหว่างองค์ประกอบ ถ้าไม่ระบุจะใช้เครื่องหมายจุลภาค (",") เป็นค่าเริ่มต้น

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
  <title>ตัวอย่าง TypedArray.join()</title>
</head>
<body>
  <script>
    const int32View = new Int32Array([21, 19, 65, 21, 14, 66, 87, 55]);
    document.write("<br>");
    
    // ไม่มีตัวคั่น (รวมต่อเนื่อง)
    let result = int32View.join('');
    document.write("ไม่มีตัวคั่น: " + result + "<br>");
    
    // ใช้เครื่องหมายทวิภาค
    result = int32View.join(':');
    document.write("ทวิภาค (:): " + result + "<br>");
    
    // ใช้ขีดกลาง
    result = int32View.join('-');
    document.write("ขีดกลาง (-): " + result + "<br>");
    
    // ใช้ช่องว่าง
    result = int32View.join(' ');
    document.write("ช่องว่าง: " + result + "<br>");
  </script>
</body>
</html>

ผลลัพธ์

ไม่มีตัวคั่น: 2119652114668755
ทวิภาค (:): 21:19:65:21:14:66:87:55
ขีดกลาง (-): 21-19-65-21-14-66-87-55
ช่องว่าง: 21 19 65 21 14 66 87 55

เมธอดนี้ทำงานคล้ายกับ Array.prototype.join() แต่เป็นเฉพาะสำหรับ TypedArray เช่น Int8Array, Uint8Array, Int32Array, Float64Array เป็นต้น