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

วิธีลบสมาชิกเฉพาะตัวออกจากอาร์เรย์ JavaScript

การลบสมาชิกเฉพาะตัวจากอาร์เรย์ ทำได้โดย:

  1. หา index ด้วย indexOf()
  2. ลบด้วย splice(index, 1)

ตัวอย่าง

<html>
  <body>
    <script>
      var array = [40, 20, 70, 50];
      var index = array.indexOf(70);

      document.write("Original array: " + array);

      if (index > -1) {
        array.splice(index, 1);
      }

      document.write("<br>New array after deletion: " + array);
    </script>
  </body>
</html>

ผลลัพธ์

Original array: 40,20,70,50
New array after deletion: 40,20,50

วิธีอื่นๆ

// 1. filter (สร้างอาร์เรย์ใหม่ ไม่แก้เดิม) - แนะนำ
const newArray = array.filter(item => item !== 70);

// 2. ลบทุกค่าที่ตรง (ถ้ามีซ้ำหลายตัว)
for (let i = array.length - 1; i >= 0; i--) {
  if (array[i] === 70) array.splice(i, 1);
}

// 3. findIndex + splice (ES6)
const idx = array.findIndex(item => item === 70);
if (idx !== -1) array.splice(idx, 1);

สรุปการเลือกใช้

วิธีแก้อาร์เรย์เดิมลบทุกค่าที่ตรงเหมาะสำหรับ
indexOf + spliceใช่ไม่ (แค่ตัวแรก)ลบ 1 ค่า แบบเร็ว
filterไม่ (สร้างใหม่)ใช่โค้ดสะอาด ไม่ต้องการ mutation
ลูปย้อนหลัง + spliceใช่ใช่ต้องแก้อาร์เรย์เดิม และลบทุกตัว