เรียนรู้วิธี append items เข้า array หลายวิธี
Append item ใช้ push() หรือ concat() ขึ้นกับ context ทั้งคู่มาจาก JavaScript Array object
Append Single Item
const vegetables = ["broccoli", "onion", "spinach"];
vegetables.push("carot");
console.log(vegetables); // ["broccoli", "onion", "spinach", "carot"]
Note: vegetables array ถูก modify
Append Multiple Items
vegetables.push("carot", "green beans", "kale");
Note: array ถูก modify
Modify Array vs New Array / push() vs concat()
push() modifies original array ถ้าอยากสร้าง new array based on original + append ใหม่ ใช้ concat():
const vegetables = ["broccoli", "onion", "spinach"];
const newVegetables = vegetables.concat("carot");
console.log(vegetables); // ["broccoli", "onion", "spinach"] (unchanged)
console.log(newVegetables); // ["broccoli", "onion", "spinach", "carot", ...]
concat() หลาย items: คั่น comma เหมือน push()
const newVegetables = vegetables.concat("carot", "green beans", "kale");
Summary
push()modifies original arrayconcat()returns (creates) new array