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

JavaScript Basic Array Methods - เมธอดพื้นฐานของอาร์เรย์


เมธอดพื้นฐาน 5 ตัวที่ต้องรู้

Methodคำอธิบายเปลี่ยน Array ต้นฉบับ?คืนค่า
push(...items)เพิ่ม element ไปท้ายอาร์เรย์ใช่ (Mutate)ความยาวใหม่
pop()ลบ element ตัวสุดท้ายใช่Element ที่ลบ (หรือ undefined)
unshift(...items)เพิ่ม element ไปหน้าอาร์เรย์ใช่ความยาวใหม่
shift()ลบ element ตัวแรกใช่Element ที่ลบ (หรือ undefined)
splice(start, deleteCount, ...items)เพิ่ม/ลบ/แทนที่ ตำแหน่งใดก็ได้ใช่Array ของ elements ที่ลบ

ตัวอย่างโค้ดครบถ้วน

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Array Methods Demo</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; }
    .panel { background: #f5f5f5; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
    .code { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 4px; font-family: monospace; overflow-x: auto; }
    .output { background: #e8f5e9; padding: 15px; border-radius: 4px; font-family: monospace; white-space: pre-wrap; }
    button { padding: 10px 20px; background: #7e32d4; color: white; border: none; border-radius: 4px; cursor: pointer; margin-right: 10px; }
    button:hover { background: #6a1b9a; }
    .method-desc { margin: 10px 0; padding: 10px; background: #fff3e0; border-left: 4px solid #ff9800; border-radius: 0 4px 4px 0; }
  </style>
</head>
<body>
  <h1>JavaScript Basic Array Methods Demo</h1>
  
  <div class="panel">
    <h3>อาร์เรย์ต้นฉบับ</h3>
    <div class="code" id="originalArray"></div>
  </div>
  
  <div class="panel">
    <h3>ทดสอบเมธอดต่างๆ</h3>
    <button onclick="demoPush()">push(99)</button>
    <button onclick="demoPop()">pop()</button>
    <button onclick="demoUnshift()">unshift(88)</button>
    <button onclick="demoShift()">shift()</button>
    <button onclick="demoSplice()">splice(2, 1, 'X', 'Y')</button>
    <button onclick="resetArray()">Reset</button>
  </div>
  
  <div class="panel">
    <h3>ผลลัพธ์</h3>
    <div class="output" id="output"></div>
  </div>

  <script>
    let arr = ['A', 'B', 1, 2, 3, 5];
    const originalEl = document.getElementById('originalArray');
    const outputEl = document.getElementById('output');
    
    function updateDisplay() {
      originalEl.textContent = 'arr = [' + arr.join(', ') + ']';
    }
    
    function log(msg) {
      outputEl.textContent += msg + '\n';
      outputEl.scrollTop = outputEl.scrollHeight;
    }
    
    function resetArray() {
      arr = ['A', 'B', 1, 2, 3, 5];
      outputEl.textContent = '';
      updateDisplay();
    }
    
    function demoPush() {
      const len = arr.push(99);
      log(`push(99) → คืนค่า: ${len} | arr: [${arr}]`);
      updateDisplay();
    }
    
    function demoPop() {
      const removed = arr.pop();
      log(`pop() → คืนค่า: ${removed} | arr: [${arr}]`);
      updateDisplay();
    }
    
    function demoUnshift() {
      const len = arr.unshift(88);
      log(`unshift(88) → คืนค่า: ${len} | arr: [${arr}]`);
      updateDisplay();
    }
    
    function demoShift() {
      const removed = arr.shift();
      log(`shift() → คืนค่า: ${removed} | arr: [${arr}]`);
      updateDisplay();
    }
    
    function demoSplice() {
      // splice(start, deleteCount, ...items)
      // เริ่ม index 2, ลบ 1 ตัว, เพิ่ม 'X', 'Y'
      const removed = arr.splice(2, 1, 'X', 'Y');
      log(`splice(2, 1, 'X', 'Y') → ลบ: [${removed}] | arr: [${arr}]`);
      updateDisplay();
    }
    
    resetArray();
  </script>
</body>
</html>

รายละเอียดแต่ละเมธอด

1. push() - เพิ่มท้าย

const fruits = ['apple', 'banana'];
fruits.push('orange');        // ['apple', 'banana', 'orange']
fruits.push('mango', 'kiwi'); // ['apple', 'banana', 'orange', 'mango', 'kiwi']

2. pop() - ลบท้าย

const fruits = ['apple', 'banana', 'orange'];
const last = fruits.pop(); // 'orange', fruits = ['apple', 'banana']

3. unshift() - เพิ่มหน้า

const fruits = ['banana', 'orange'];
fruits.unshift('apple'); // ['apple', 'banana', 'orange']

4. shift() - ลบหน้า

const fruits = ['apple', 'banana', 'orange'];
const first = fruits.shift(); // 'apple', fruits = ['banana', 'orange']

5. splice() - ทำได้ทุกอย่าง (เพิ่ม/ลบ/แทนที่)

const arr = [1, 2, 3, 4, 5];

// ลบ 2 ตัว ตั้งแต่ index 1 (คือ 2, 3)
arr.splice(1, 2); // [1, 4, 5] - คืนค่า [2, 3]

// แทนที่ 1 ตัว ที่ index 1 ด้วย 'X'
arr.splice(1, 1, 'X'); // [1, 'X', 4, 5] - คืนค่า [4]

// เพิ่ม 'Y', 'Z' ที่ index 2 โดยไม่ลบอะไร
arr.splice(2, 0, 'Y', 'Z'); // [1, 'X', 'Y', 'Z', 4, 5] - คืนค่า []

เมธอดที่ไม่เปลี่ยน Array ต้นฉบับ (Immutable)

หากต้องการไม่ mutate array เดิม ใช้เมธอดเหล่านี้:

Immutable Methodเทียบเท่า Mutating
arr.concat(...items)push (แต่คืน array ใหม่)
arr.slice()splice (สำหรับลบ/คัดลอก)
[...arr, newItem] (Spread)push
[newItem, ...arr]unshift
arr.filter(...)splice (ลบตามเงื่อนไข)
arr.map(...)splice (แปลงค่า)
arr.toSorted() (ES2023)arr.sort()
arr.toReversed() (ES2023)arr.reverse()
arr.with(index, value) (ES2023)arr[index] = value

Performance Note

  • push/pop เร็วที่สุด (O(1)) - ทำงานที่ปลายอาร์เรย์
  • shift/unshift ช้ากว่า (O(n)) - ต้องเลื่อน index ทุกตัว
  • splice O(n) - ขึ้นอยู่กับตำแหน่งและจำนวนที่ลบ/เพิ่ม
  • สำหรับ Queue ใช้ push + shift (แต่ shift ช้า)
  • สำหรับ Stack ใช้ push + pop (เร็วที่สุด)