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

JavaScript Objects: คู่มือสร้าง อ่าน แก้ไข ลบ Properties

Object ใน JavaScript เก็บข้อมูลเป็น Key-Value pairs ใส่ฉลากข้อมูลได้ เข้าถึงง่าย ใช้แทน Array หลายมิติ

สร้าง Object

// Object Literal (แนะนำ)
const cookie = {};

// Object Constructor
const cookie = new Object();

// พร้อมข้อมูล
const raspberry_white_choc = {
  name: "Raspberry White Chocolate Chip",
  price: 1.50,
  available: true,
  stock: 42
};

อ่านค่า Property

// Dot notation
console.log(raspberry_white_choc.name); // "Raspberry White Chocolate Chip"

// Bracket notation
console.log(raspberry_white_choc["available"]); // true

Bracket notation ใช้ได้กับ key ที่มี space หรือตัวแปร

แก้ไข Object

เพิ่ม Property

// Dot
raspberry_white_choc.gluten_free = false;

// Bracket
raspberry_white_choc["gluten_free"] = false;

แก้ไข Property เดิม

raspberry_white_choc.gluten_free = true; // เปลี่ยนเป็น true

ลบ Property

delete raspberry_white_choc.gluten_free;
// { name: "...", price: 1.5, available: true, stock: 42 }

สรุป

  • Object เก็บข้อมูล key-value ใช้ { } สร้าง
  • เข้าถึงด้วย . หรือ []
  • เพิ่ม/แก้ = กำหนดค่าใหม่ ลบ = delete keyword
  • Value เป็นได้ทุกประเภท รวมถึง Function (Method)