Stay Informed

พื้นฐานของ JavaScript : Array และ Object

 

📌 พื้นฐานของ JavaScript : Array และ Object


1️⃣ Array คืออะไร?

  • คือ ตัวแปรที่เก็บข้อมูลหลายค่าไว้ในตัวแปรเดียว

  • ข้อมูลภายในสามารถเป็นได้ทุกชนิด (string, number, object, function, array)

การประกาศ Array

javascript

let fruits = ["มะม่วง", "ส้ม", "กล้วย"]; let numbers = [1, 2, 3, 4, 5]; let mixed = [1, "มิว", true, null];

การเข้าถึงสมาชิกใน Array

  • ใช้ index (ตำแหน่ง) โดย index เริ่มที่ 0

javascript

console.log(fruits[0]); // "มะม่วง" console.log(fruits[2]); // "กล้วย"

การเพิ่ม/ลบข้อมูลใน Array

คำสั่ง ความหมาย ตัวอย่าง
push() เพิ่มท้าย fruits.push("แตงโม")
pop() ลบจากท้าย fruits.pop()
unshift() เพิ่มหน้าสุด fruits.unshift("สับปะรด")
shift() ลบจากหน้าสุด fruits.shift()

ตัวอย่าง
javascript

fruits.push("แตงโม"); console.log(fruits); // ["มะม่วง", "ส้ม", "กล้วย", "แตงโม"]

วนลูป Array

javascript

for (let fruit of fruits) { console.log(fruit); }

2️⃣ Object คืออะไร?

  • คือ กลุ่มของข้อมูลแบบ key-value (property)

  • ใช้เก็บข้อมูลที่มีความสัมพันธ์กัน

การประกาศ Object

javascript

let person = { name: "มิว", age: 25, isStudent: true };

การเข้าถึงข้อมูลใน Object

  • แบบ dot notation

javascript

console.log(person.name); // "มิว"
  • แบบ bracket notation

javascript

console.log(person["age"]); // 25

การเพิ่ม/แก้ไขค่าใน Object

javascript

person.gender = "ชาย"; // เพิ่ม property ใหม่ person.age = 26; // แก้ไขค่า

การลบ property

javascript

delete person.isStudent;

วนลูป Object

javascript

for (let key in person) { console.log(key + ": " + person[key]); }

3️⃣ Array vs Object

จุดเปรียบเทียบ Array Object
รูปแบบข้อมูล ลำดับข้อมูล key-value
index เป็นตัวเลข เป็น string หรือ symbol
เหมาะกับ กลุ่มข้อมูล เก็บข้อมูลแบบมีรายละเอียด

ตัวอย่างใช้งานร่วมกัน
javascript

let people = [ { name: "มิว", age: 25 }, { name: "นัท", age: 30 }, { name: "โบ๊ท", age: 28 } ]; for (let person of people) { console.log(person.name + " อายุ " + person.age); }

4️⃣ เมธอดของ Array ที่ใช้บ่อย

เมธอด ตัวอย่าง ความหมาย
length fruits.length นับจำนวนสมาชิก
indexOf() fruits.indexOf("ส้ม") หา index ของค่า
includes() fruits.includes("กล้วย") ตรวจสอบว่ามีค่าหรือไม่
slice() fruits.slice(1, 3) ตัดบางส่วนของ Array
splice() fruits.splice(1, 1) ลบ/เพิ่มค่ากลาง Array
map() numbers.map(n => n*2) สร้าง Array ใหม่
filter() numbers.filter(n => n>2) คัดกรองค่า
forEach() fruits.forEach(f => console.log(f)) วนลูป




🎯 สรุปแบบง่าย
Array Object
เก็บชุดข้อมูลที่เป็นลำดับ เก็บข้อมูลรายละเอียดเป็น key-value
เข้าถึงด้วย index เข้าถึงด้วย key
ใช้งานกับ for, for...of ใช้งานกับ for...in







✅ ตัวอย่างสรุปรวม

javascript

let student = { name: "มิว", subjects: ["คณิต", "วิทย์", "อังกฤษ"], age: 25 }; console.log(student.name); // "มิว" console.log(student.subjects[1]); // "วิทย์" student.subjects.push("ประวัติศาสตร์"); console.log(student.subjects);

      



Facebook Comment