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

4 วิธีล้างอาร์เรย์ (Empty Array) ใน JavaScript


การว่างเปล่าอาร์เรย์ใน JavaScript มีหลายวิธี แต่พฤติกรรมต่างกัน: บางวิธีสร้างอาร์เรย์ใหม่ บางวิธีแก้ไขอาร์เรย์เดิม (Mutate) การเลือกขึ้นอยู่กับว่า Variable เป็น const หรือ let และว่ามี Reference อื่นชี้ไปที่อาร์เรย์เดิมหรือไม่

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Empty Array Methods</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: blueviolet; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>4 วิธีล้างอาร์เรย์ใน JavaScript</h1>
  <div class="sample">a=[1,2,3,4], b=['a','b','c'], c=['A','B','C','D'], d=[11,22,33,44]</div>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อล้างอาร์เรย์ทั้ง 4 ด้วยวิธีต่างกัน</h3>
  <script>
    const resEle = document.querySelector(".result");
    let a = [1, 2, 3, 4];
    let b = ["a", "b", "c"];
    let c = ["A", "B", "C", "D"];
    let d = [11, 22, 33, 44];
    document.querySelector(".Btn").addEventListener("click", () => {
      // 1. กำหนด Array ใหม่ (Reassignment) - ต้องใช้ let
      a = [];
      resEle.innerHTML = "a = [] → " + a + "<br>";
      // 2. ตั้ง length = 0 (Mutate) - ใช้ได้กับ const
      b.length = 0;
      resEle.innerHTML += "b.length = 0 → " + b + "<br>";
      // 3. Pop ซ้ำจนหมด (Mutate)
      while (c.length > 0) c.pop();
      resEle.innerHTML += "while pop → " + c + "<br>";
      // 4. Splice ตั้งแต่ต้น (Mutate)
      d.splice(0, d.length);
      resEle.innerHTML += "d.splice(0, d.length) → " + d + "<br>";
    });
  </script>
</body>
</html>

ผลลัพธ์

4 วิธีล้างอาร์เรย์ (Empty Array) ใน JavaScript

เมื่อกดปุ่ม "คลิกที่นี่":

4 วิธีล้างอาร์เรย์ (Empty Array) ใน JavaScript

เปรียบเทียบ 4 วิธี

วิธีCodeMutate?const OK?Reference อื่นได้รับผล?Performance
1. Reassignmentarr = []❌ (สร้างใหม่)❌ (ต้อง let)❌ (Reference เก่ายังคงอาร์เรย์เก่า)เร็วที่สุด
2. Length = 0arr.length = 0✅✅✅ (Reference ทุกตัวเห็นว่าง)เร็ว
3. Pop Loopwhile(arr.length) arr.pop()✅✅✅ช้า (Loop O(n))
4. Splicearr.splice(0, arr.length)✅✅✅เร็ว (Native)

เมื่อไหร่ใช้วิธีไหน?

  • Reassignment (arr = []): ตัวแปรเป็น let ไม่มี Reference อื่นชี้ไป — เร็วที่สุด สะอาดที่สุด
  • Length = 0: ตัวแปรเป็น const หรือมี Reference อื่นต้องเห็นการเปลี่ยนแปลง — มาตรฐาน สำหรับ Mutate
  • Splice: ต้องการคืนค่าที่ลบออกมา (แม้ว่าจะไม่ได้ใช้ในที่นี้)
  • Pop Loop: ไม่แนะนำสำหรับล้างทั้งหมด (ช้า) — ใช้สำหรับลบทีละตัวพร้อมประมวลผล

⚠️ ข้อผิดพลาดที่พบบ่อย

// ❌ ผิด: const arr = [1,2,3]; arr = []; // TypeError: Assignment to constant variable
// ✅ ถูก: const arr = [1,2,3]; arr.length = 0;

// ❌ ผิด: คิดว่า arr = [] จะล้าง Reference อื่น
const a = [1,2,3];
const b = a;
a = []; // b ยังคงเป็น [1,2,3]!

// ✅ ถ้าต้องการให้ b เห็นการเปลี่ยนแปลง
const a = [1,2,3];
const b = a;
a.length = 0; // b ก็เป็น [] ด้วย

ล้าง Array-like Objects (Arguments, NodeList)

// Arguments object (Array-like)
function foo() {
  const args = Array.from(arguments);
  args.length = 0; // Works
}

// NodeList - ไม่มี length setter
const nodes = document.querySelectorAll("div");
// nodes.length = 0; // Error: read-only
// ต้องแปลงเป็น Array ก่อน
[...nodes].forEach(n => n.remove());