ฟังก์ชัน fill() ของ TypedArray ใช้ เติมค่าคงที่ ลงในช่วงของอาเรย์ (หรือทั้งอาเรย์) แทนที่ค่าเดิม
ไวยากรณ์
typedArray.fill(value[, start[, end]])
ตัวอย่าง
<html> <head> <title>JavaScript Array fill Method</title> </head> <body> <script type="text/javascript"> var int32View = new Int32Array([64, 89, 65, 21, 14, 66, 87, 55]); document.write("เนื้อหาเดิม: "+int32View); document.write("<br>"); int32View.fill(464, 3); document.write("หลัง fill(464, 3): "+int32View); </script> </body> </html>
ผลลัพธ์
เนื้อหาเดิม: 64,89,65,21,14,66,87,55 หลัง fill(464, 3): 64,89,65,464,464,464,464,464
พารามิเตอร์:
value: ค่าที่จะเติม (จะถูกแปลงให้เข้ากับชนิด TypedArray)start (optional): เริ่มต้นที่ index นี้ (default 0) - รองรับ negative indexend (optional): หยุดก่อน index นี้ (default length) - รองรับ negative index
ตัวอย่างเพิ่มเติม:
const arr = new Int32Array([1, 2, 3, 4, 5]); arr.fill(0); // [0, 0, 0, 0, 0] arr.fill(9, 1); // [0, 9, 9, 9, 9] arr.fill(8, 1, 3); // [0, 8, 8, 9, 9] arr.fill(7, -3, -1); // [0, 8, 7, 7, 9] (negative index)
ข้อแตกต่างจาก Array.fill():
- ทำงานเหมือนกัน แต่ TypedArray มี type constraint
- ค่า value จะถูกแปลง (convert/truncate) ให้เข้ากับชนิด (เช่น Int32Array รับเฉพาะ integer)
- เปลี่ยนค่าในตัว (mutates) คืนค่า typed array เดียวกัน