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

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

TypedArray.slice()

เมธอด slice() สร้าง Typed Array ใหม่ที่เป็นสำเนาของส่วนที่ระบุ (Shallow Copy) โดยรับพารามิเตอร์ begin และ end (ไม่รวม) คล้าย Array.slice()

ไวยากรณ์

typedArray.slice(begin, end)

ตัวอย่าง

<html> <body> <script>
  var typedArray = new Int32Array([11, 5, 13, 4, 15, 3, 17, 2, 19, 8]);
  document.write("Contents of the typed array: " + typedArray);
  document.write("<br>");
  var resultantArray = typedArray.slice(2, 7); // Index 2 ถึง 6
  document.write("Resultant Array: " + resultantArray);
</script> </body> </html>

ผลลัพธ์

Contents of the typed array: 11,5,13,4,15,3,17,2,19,8
Resultant Array: 13,4,15,3,17

ความแตกต่างจาก subarray(): slice() สร้าง Buffer ใหม่ (Copy Data) ในขณะที่ subarray() แบ่งปัน Buffer เดียวกัน (View) การแก้ไข slice() ไม่กระทบ Array ต้นฉบับ