ArrayBuffer.slice() คืออะไร
เมธอด ArrayBuffer.prototype.slice() ใช้สำหรับ สร้าง ArrayBuffer ใหม่ ที่มีข้อมูลเป็นส่วนหนึ่ง (subset) ของ ArrayBuffer เดิม เมธอดนี้รับพารามิเตอร์ 2 ตัว คือ ตำแหน่งเริ่มต้น (start, inclusive) และตำแหน่งสิ้นสุด (end, exclusive) แล้วคืน ArrayBuffer ใหม่ที่มีข้อมูลคัดลอกมาจากช่วงที่ระบุ
สำคัญ: ArrayBuffer ใหม่ที่ได้เป็นอิสระจาก ArrayBuffer เดิม การเปลี่ยนแปลงข้อมูลใน ArrayBuffer ใหม่จะไม่ส่งผลต่อ ArrayBuffer เดิม และในทางกลับกัน
ไวยากรณ์ (Syntax)
arrayBuffer.slice(begin[, end])
begin- ตำแหน่งเริ่มต้น (0-indexed, inclusive) ค่า default = 0end- ตำแหน่งสิ้นสุด (exclusive) ค่า default =arrayBuffer.byteLength
คืนค่า: ArrayBuffer ใหม่ที่มีข้อมูลคัดลอกจากช่วงที่ระบุ
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: การ slice พื้นฐาน
const buffer = new ArrayBuffer(16);
const view = new Int32Array(buffer);
view[0] = 10;
view[1] = 20;
view[2] = 30;
view[3] = 40;
// ตัดเฉพาะส่วนกลาง (bytes 4-11 = int32 index 1-2)
const sliced = buffer.slice(4, 12);
const slicedView = new Int32Array(sliced);
console.log(slicedView[0]); // 20
console.log(slicedView[1]); // 30
console.log(sliced.byteLength); // 8 bytes
ตัวอย่างที่ 2: การใช้ค่า default และค่าลบ
const buffer = new ArrayBuffer(16);
const view = new Uint8Array(buffer);
for (let i = 0; i < 16; i++) view[i] = i + 1;
// เริ่มจาก byte ที่ 4 จนถึงสุดท้าย
const from4 = buffer.slice(4);
console.log(from4.byteLength); // 12
// ใช้ index ลบ (นับจากท้าย)
const last8 = buffer.slice(-8);
console.log(last8.byteLength); // 8
// ช่วงกลางด้วย index ลบ
const middle = buffer.slice(4, -4);
console.log(middle.byteLength); // 8
ตัวอย่างที่ 3: การใช้กับ Typed Arrays ที่ต่างกัน
const buffer = new ArrayBuffer(24);
const int32 = new Int32Array(buffer);
int32[0] = 0x12345678;
int32[1] = 0x9ABCDEF0;
int32[2] = 0x11223344;
// ตัดเฉพาะ int32 ตัวที่ 2 (bytes 8-11)
const part = buffer.slice(8, 12);
const uint16 = new Uint16Array(part);
console.log(uint16[0].toString(16)); // def0 (little-endian)
console.log(uint16[1].toString(16)); // 9abc
ความแตกต่างระหว่าง ArrayBuffer.slice() และ TypedArray.slice()
| คุณสมบัติ | ArrayBuffer.slice() | TypedArray.slice() |
|---|---|---|
| คืนค่า | ArrayBuffer ใหม่ | TypedArray ใหม่ (ชนิดเดียวกัน) |
| หน่วยของ index | Byte | Element |
| คัดลอกข้อมูล | ✅ ใช่ | ✅ ใช่ |
| รองรับ index ลบ | ✅ ใช่ | ✅ ใช่ |
กรณีการใช้งานทั่วไป (Use Cases)
- Protocol parsing: ตัด header/body จาก network buffer
- File processing: อ่านเฉพาะ chunk ของไฟล์ขนาดใหญ่
- Zero-copy (near): ส่งเฉพาะส่วนที่ต้องการไปให้ Web Worker
- Data transformation: แปลงข้อมูลบางส่วนโดยไม่กระทบต้นฉบับ
ข้อควรระวัง
- การ slice สร้าง ArrayBuffer ใหม่และคัดลอกข้อมูล (copy) - ใช้หน่วยความจำเพิ่ม
- สำหรับข้อมูลขนาดใหญ่ ควรพิจารณาใช้
DataViewหรือ typed array view แทน เพื่อหลีกเลี่ยงการคัดลอก - Index ลบจะนับจากท้าย:
-1= ไบต์สุดท้าย,-8= 8 ไบต์จากท้าย