ใช้ splice() แทนที่ element ที่ index ที่กำหนด
splice(start, deleteCount, ...items) ลบและ/หรือเพิ่ม element ที่ตำแหน่ง start
ตัวอย่างโค้ด
var changePosition = 2; // index ที่ 2 (0-based: John=0, David=1, Mike=2)
var listOfNames = ['John', 'David', 'Mike', 'Sam', 'Carol'];
console.log("ก่อนแทนที่ = ");
console.log(listOfNames);
var name = 'Adam';
var result = listOfNames.splice(changePosition, 1, name); // ลบ 1 ตัว ใส่ 'Adam'
console.log("หลังแทนที่ = ");
console.log(listOfNames);
// ['John', 'David', 'Adam', 'Sam', 'Carol']
วิธีรัน
node fileName.js
ผลลัพธ์
ก่อนแทนที่ = [ 'John', 'David', 'Mike', 'Sam', 'Carol' ]
หลังแทนที่ = [ 'John', 'David', 'Adam', 'Sam', 'Carol' ]
คำอธิบาย splice()
splice(index, count, ...items)index: เริ่มที่ตำแหน่งนี้ (0-based)count: จำนวน element ที่จะลบ (0 = ไม่ลบ แค่แทรก)...items: element ใหม่ที่จะแทรก- คืนค่า: อาร์เรย์ของ element ที่ถูกลบออก
- Mutates original array (เปลี่ยนอาร์เรย์ต้นฉบับ)
ตัวอย่างเพิ่มเติม
// แทรกโดยไม่ลบ (insert at index 2)
arr.splice(2, 0, 'New');
// ลบ 2 ตัว แทรก 3 ตัว
arr.splice(1, 2, 'A', 'B', 'C');
// ลบทั้งหมดตั้งแต่ index 2
arr.splice(2);