본문 바로가기
프로그래밍

자바스크립트 : Array, Loops, and Objects II (코드카데미)

by Youngbin Kwon 2020. 8. 12.

공부 출처 : 코드카데미 (참조) 강의 (5. Javascript: Arrays, Loops, and Objects)

 

Objects (객체)

1. 객체의 선언 및 기본 구조

const classOf2018 = {
  students: 38,
  year: 2018
}

객체는 {}문으로 둘러싸여지며, Key : Value 형태로 이루어진다.

 

2. 객체의 Value(프로퍼티값) 가져오기

const apple = { 
  color: 'Green',
  price: {
    bulk: '$3/kg',
    smallQty: '$4/kg'
  }
};
console.log(apple.color); // 'Green'
console.log(apple.price.bulk); // '$3/kg'

객채 프로퍼티 값을 가져오기 위해 Object.propertyName의 형태로 불러올 수 있다. (Object[propertyName]도 가능

 

3. 객체 프로퍼티 삭제

Delete Object.propertyName 을 통해 삭제할 수 있다.

const person = {
  firstName: "Matilda",
  age: 27,
  hobby: "knitting",
  goal: "learning JavaScript"
};

delete person.hobby; // or delete person[hobby];

console.log(person);
/*
{
  firstName: "Matilda"
  age: 27
  goal: "learning JavaScript"
}
*/

4. 객체는 Mutable 하다

const student = {
  name: 'Sheldon',
  score: 100,
  grade: 'A',
}

console.log(student)
// { name: 'Sheldon', score: 100, grade: 'A' }

delete student.score
student.grade = 'F'
console.log(student)
// { name: 'Sheldon', grade: 'F' }

student = {}
// TypeError: Assignment to constant variable.

Const로 선언하여도 객체 내부의 프로퍼티값은 삭제 또는 추가 등이 가능하다.

 

5. For ... in 루프문

let mobile = {
  brand: 'Samsung',
  model: 'Galaxy Note 9'
};

for (let key in mobile) {
  console.log(`${key}: ${mobile[key]}`);
}

For... in 문을 통해 객체 내부의 각각의 키값에 대해 지시할 수 있다.

 

6. this

const restaurant = {
  numCustomers: 45,
  seatCapacity: 100,
  availableSeats() {
    // this refers to the restaurant object
    // and it's used to access its properties
    return this.seatCapacity - this.numCustomers;
  }
}

모든 자바스크립트 함수/메소드는 this를 사용할 수 있으며, this는 this가 선언된 객체를 지칭한다. 객체 바깥에서 선언되는 this는 전역 요소(브라우저의 경우에는 window창, Node.js 환경에서는 global)을 지칭한다.

 

7. 객체 선언의 다른 방법

const rubiksCubeFacts = {
  possiblePermutations: '43,252,003,274,489,856,000',
  invented: '1974',
  largestCube: '17x17x17'
};
const {possiblePermutations, invented, largestCube} = rubiksCubeFacts;
console.log(possiblePermutations); // '43,252,003,274,489,856,000'
console.log(invented); // '1974'
console.log(largestCube); // '17x17x17'
const activity = 'Surfing';
const beach = { activity };
console.log(beach); // { activity: 'Surfing' }

위 두 방법으로도 객체를 선언할 수 있다.

댓글