แทรกท้าย array ใช้ push แทรกหน้า array ใช้ unshift แทรกตำแหน่งอื่นใช้ splice
Push
ตัวอย่าง
let arr = ["test", 1, 2, "hello", 23.5]; arr.push(123); console.log(arr);
ผลลัพธ์
[ 'test', 1, 2, 'hello', 23.5, 123 ]
Unshift
ตัวอย่าง
let arr = ["test", 1, 2, "hello", 23.5]; arr.unshift(123); console.log(arr);
ผลลัพธ์
[ 123, 'test', 1, 2, 'hello', 23.5 ]
Splice
splice() เปลี่ยนเนื้อหา array โดยลบ/แทนที่ elements และ/หรือเพิ่ม elements ใหม่ ใช้ insert ที่ index ได้ดังนี้
ตัวอย่าง
let arr = ["test", 1, 2, "hello", 23.5]; // Replace 0 elements (insert) at index 2 with 123 arr.splice(2, 0, 123); console.log(arr);
ผลลัพธ์
[ 'test', 1, 123, 2, 'hello', 23.5 ]