JS레플릿 26. Object -다시:)

송철진·2022년 10월 21일
0

Assignment

getAnswer 함수를 구현해 주세요.
getAnswer 함수는 아래의 객체에서 '샐러드' 라는 값을 출력합니다.

결과

let myProfile = {
  name: '김개발',
  address: {
    email: 'geabal@gmail.com',
    home: '위워크'
  },
  'my favorite': {
    food: [{
      name: '샐러드',
      price: 3500
    }, {
      name: '삼겹살',
      price: 15000
    }],
    hobby: ['축구']
  }
}

// getAnswer 함수를 호출하면
// '샐러드'가 return 될 수 있도록 프로퍼티에 접근해서 반환해주세요.
function getAnswer() {
  return myProfile['my favorite'].food[0].name;
}
console.log(getAnswer());

1. 객체 리터럴

객체는 다른 데이터 타입(텍스트, 숫자, 배열 등..)처럼 변수에 저장할 수 있다
object literal(객체 리터럴) : {} 으로 생긴 모양의 객체
객체는 키(key)-값(value) 쌍으로된 데이터의 모음으로써 순서가 뒤 바뀌어도 아무 상관이 없습니다.
key는 property name이라고도 하며, value는 property value

객체의 키에는 스페이스, 한글, 특수문자 등이 들어갈 수 있습니다.
키에 특수문자가 없으면 따옴표를 생략

let difficult = {
  'my name': 'boong',
  color: 'silver',: '한글인 키는 따옴표가 없어도 되는군!!',
  '!키': '느낌표 있는 키는 따옴표가 필요하군',
  $special: '$는 없어도 되는군'
};

2. 프로퍼티 접근

dot(.)으로 접근하는 방법과 [] 대괄호로 접근하는 법

let difficult = {
  color: 'silver',
  "color pen": 0,
  33: '1234'
};
console.log(difficult.color); // "silver"
console.log(difficult['color']); // "silver"
// 숫자와 띄어쓰기는 대괄호[]로 접근한다
console.log(difficult['33']); 
console.log(difficult['color pen']); 

3. 변수로 프로퍼티 접근

let difficult = {
  color: 'silver',
  "color pen": 0,: 'Key'
};
let name = '키';
// 변수 접근할 때는 항상 대괄호[]를 사용한다
console.log(difficult[name]); // "Key"
// 실제 키 이름을 쓸 때만 dot(.)으로 접근한다
console.log(difficult.name); // undefined: "name"이라는 키가 없으므로 

4. 프로퍼티 할당

  • 객체에 이미 키가 존재하는데, 다시 한 번 할당하면 값이 교체(수정)됩니다.
  • 이전에 없던 키로 접근하면, 새로운 프로퍼티가 추가됩니다
  • 이 때 값은 undefined입니다
  • const 로 선언된 변수에 객체를 다시 할당하면 오류가 생기지만,
    그 객체에 프로퍼티를 추가하거나 수정하는 것은 가능합니다
const mutableObj = {
  name: '객체'
};

//const 로 선언된 변수에 객체를 다시 할당하면 오류
mutableObj = {
   name: '수정'
}
//프로퍼티를 추가하거나 수정하는 것은 가능; 아래 결과 확인
mutableObj.name = '수정';
mutableObj.type = 'Object 타입';

5. Method (메서드)

메서드: 객체에 저장된 함수

  • 예) console.log() : global 객체; js 어디에서나 접근 가능하므로
    logconsole 이라는 객체의 메서드
//메서드의 선언
let methodObj = {
  do: function() {
    console.log('메서드 정의는 이렇게');
  }
}
//메서드의 호출
methodObj.do();

6. 중첩된 객체 (Nested Object)

let nestedObj = {
	type: {
		year: '2019',
		'comment-type': [{
			name: 'simple'
		}]
	}
}
//"simple"
console.log(nestedObj.type['comment-type'][0].name); 
//"2019"
console.log(nestedObj.type.year);
//"[{name: 'simple'}]"
console.log(nestedObj.type.['comment-type'];
//"{name: 'simple'}"
console.log(nestedObj.type.['comment-type'][0]);

7. 객체는 reference로 저장된다.

객체를 변수에 저장하면 객체 자체가 저장되는 것이 아니라 reference가 저장됩니다.

Q. 눈에 보이는 값은 '안녕'으로 똑같은데 다르다고 하는 이유?

const hiObj = { 
  name: '안녕' 
};
const helloObj = {
  name: '안녕'
};
console.log('객체비교 =>', hiObj === helloObj); // false

A. 객체는 변수에 저장할 때, 객체 자체를 그대로 저장하는 것이 아니라
객체가 담긴 어느 메모리의 reference 를 저장하기 때문이다

hiObj 가 갖고 있는 진짜 값은 reference(메모리 주소)이지만
hiObj 를 불러오면 그 메모리에 저장된 데이터를 반환합니다.

// false: reference를 서로 비교하므로
console.log('객체비교 =>', hiObj === helloObj); 
// true: 내부 프로퍼티(텍스트)를 비교하므로
console.log('객체값비교 =>', hiObj.name === helloObj.name); 

정리:

//const 객체에서
const mutableObj = {
  name: '객체'
};

// 새로운 객체를 할당하면 진짜값인 reference가 변하므로 오류!
mutableObj = {
   name: '수정'
}

// 내부 프로퍼티를 할당하는 건 가능!
mutableObj.name = '수정 됩니다!';
profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글