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

Object ใน JavaScript และการเข้าถึง Property

JavaScript Object และการเข้าถึง Property

ใน JavaScript ทุกอย่างเกือบจะเป็น Object (Functions, Arrays, Dates, Regex ฯลฯ) เข้าถึง Property ได้ 2 วิธี

1. Dot Notation (.)

obj.propertyName

2. Bracket Notation ([])

obj['propertyName']
obj[variableWithKeyName]

ตัวอย่าง 1: เข้าถึง Nested Property

<script>
  const myObj = {
    name: 'Ramesh',
    age: 30,
    family: [{mother: 'Geetha', father: 'Rao'}],
    city: 'Berlin'
  };
  
  const motherName = myObj.family[0].mother;
  document.write(motherName); // Geetha
</script>

ตัวอย่าง 2: เข้าถึง Property ธรรมดา

<script>
  const city = myObj.city;
  document.write(city); // Berlin
</script>

เมื่อไหร่ต้องใช้ Bracket Notation?

  • Key มีช่องว่าง: obj['first name']
  • Key เป็นตัวเลข: arr[0]
  • Key อยู่ในตัวแปร: const key = 'name'; obj[key]
  • Key เป็น Reserved Word: obj['class']

Optional Chaining (ES2020)

const city = myObj?.family?.[0]?.city; // ไม่ Error ถ้า family ไม่มี