เมธอด push()
Array.push() เพิ่ม Element หนึ่งหรือหลายตัวที่ ท้าย Array และ คืนค่า Length ใหม่ (Mutate Original)
Syntax
array.push(element1, element2, ..., elementN);
ตัวอย่างโค้ด
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script>
var numbers = new Array(30, 70, 75, 90);
var length = numbers.push(100);
document.write("new numbers are : " + numbers);
length = numbers.push(200);
document.write("<br />new numbers are : " + numbers);
</script>
</body>
</html>
ผลลัพธ์
new numbers are : 30,70,75,90,100 new numbers are : 30,70,75,90,100,200
รายละเอียด
- เพิ่ม Element ต่อท้าย (Index = Length เดิม)
- เพิ่มได้หลายตัวพร้อมกัน:
arr.push(1, 2, 3) - คืนค่า Length ใหม่ (ไม่ใช่ Array)
- Mutate Original Array
ตัวอย่างการใช้งานจริง: Queue (FIFO) / Stack (LIFO)
// Stack (LIFO) - ใช้ push/pop const stack = []; stack.push(1); stack.push(2); console.log(stack.pop()); // 2 // Queue (FIFO) - ใช้ push/shift (แต่ shift ช้า O(n)) const queue = []; queue.push(1); queue.push(2); console.log(queue.shift()); // 1 // สำหรับ Queue จริง ควรใช้ Circular Buffer หรือ Linked List
วิธีที่ไม่ Mutate (Immutable)
1. Spread Operator (ES6+)
const arr = [1, 2, 3]; const newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
2. concat()
const newArr = arr.concat([4, 5]);
3. ใช้ toSpliced() (ES2023+) - แทน splice
const newArr = arr.toSpliced(arr.length, 0, 4, 5);
ตารางเปรียบเทียบ
| วิธี | Mutate? | คืนค่า | Performance |
|---|---|---|---|
push() | ใช่ | New Length | O(1) Amortized - เร็วที่สุด |
[...arr, x] | ไม่ | New Array | O(n) - Copy ทั้ง Array |
concat() | ไม่ | New Array | O(n) |
ข้อควรระวัง
push()เร็วที่สุดสำหรับการเพิ่มท้าย (Amortized O(1))- คืนค่า Length ไม่ใช่ Array:
var newArr = arr.push(x)จะได้ Number - ใช้กับ Array-like Object ได้ด้วย
Array.prototype.push.call(obj, val)
สรุป
push() เป็นวิธีมาตรฐานเพิ่ม Element ท้าย Array Mutate ต้นฉบับ คืนค่า Length ใหม่ เร็วที่สุด (O(1)) สำหรับ Immutable ใช้ Spread [...arr, newItem]