[자바스크립트] 객체

맹뿌·2021년 6월 11일
0

자바스크립트

목록 보기
5/8

객체

1. 프로퍼티

프로퍼티 키로 프로퍼티를 식별하며,
프로퍼티 키를 중복으로 선언할 경우 나중에 선언한 프로퍼티가 먼저 선언한 프로퍼티를 덮어씀.

var grades = {
    // 프로퍼티로 배열과 다르게 순서가 없음.
    'list' : {'happy': 99, 'sad': 88,'soso':12},

    'show' : function(){
	alert("Nice!");
    }
}

2. 메소드

var grades = {
    'list' : {'happy': 99, 'sad': 88,'soso':12},

    // 메소드는 객체 안에 정의된 함수로, 일반 함수와 구분하기 위함.
    'show' : function(){
	alert("Nice!");
    }
}

객체 선언 방식

var person = {
  name: 'Lee',
  gender: 'male',
  sayHello: function () {
    console.log('Hi! My name is ' + this.name);
  }
};

객체 프로퍼티 접근

1. 프로퍼티 키

var person = {
  'first-name': 'Ung-mo',
  'last-name': 'Lee',
  gender: 'male',
  1: 10,
  function: 1 // OK. 하지만 예약어는 사용하지 말아야 한다.
};

위의 코드에서 first-name과 같은 프로퍼티 키는 이름에 연산자가 포함된, 자바스크립트에서 유효하지 않은 이름이기 때문에 작은 따옴표나 큰 따옴표가 필요. 그러나 first_name 같은 경우는 유효한 이름이기에 따옴표가 생략 가능하다.

2. 프로퍼티 값 읽기

console.log(person.first-name);    // NaN: undefined-undefined
console.log(person[first-name]);   // ReferenceError: first is not defined
console.log(person['first-name']); // 'Ung-mo'

console.log(person.gender);    // 'male'
console.log(person[gender]);   // ReferenceError: gender is not defined
console.log(person['gender']); // 'male'

console.log(person['1']); // 10
console.log(person[1]);   // 10 : person[1] -> person['1']
console.log(person.1);    // SyntaxError

프로퍼티 키가 gender와 같이 유효한 자바스크립트 이름이고 예약어가 아닌 경우 프로퍼티 값은 마침표 표기법, 대괄호 표기법 모두 사용할 수 있음

프로퍼티 이름이 유효한 자바스크립트 이름이 아니거나 예약어인 경우 프로퍼티 값은 대괄호 표기법으로 읽어야 함. 대괄호([]) 표기법을 사용하는 경우, 대괄호 내에 들어가는 프로퍼티 이름은 반드시 문자열이어야 함.

3. 프로퍼티 값 갱신

person['first-name'] = 'Kim';

프로퍼티에 새로운 값을 할당하면 해당 프로퍼티는 'Kim'이라는 새로운 값으로 갱신된다.

4. 프로퍼티 동적 생성

person.age = 20;
console.log(person.age);   // 20

객체가 소유하지 않은 프로퍼티 키에 값을 할당하면 객체는 해당 프로퍼티 키와 값을 추가하여 갱신된다.

5. 프로퍼티 삭제

delete person.gender;

delete 명령어로 프로퍼티를 삭제할 수 있음. 피연산자는 프로퍼티 키여야 함.

6. for-in문

// index에 배열의 경우 인덱스가 반환된다
for (var index in array) {
  console.log(index + ': ' + array[index]);
}

for-in문은 배열에는 사용하지 않는 것을 권장

7. for-of문

const arr = [10, 20, 30];

for (const item of arr) {
    console.log(item); // 10, 20, 30 출력
}

for-of문은 배열에도 사용 가능


🎁 참조 및 출처

profile
무엇이든 할 수 있고, 무엇이든 될 수 있는

0개의 댓글