기본 문법| 객체

셀라문·2022년 2월 16일
0

JavaScript

목록 보기
6/27

객체 (Object)

중괄호 {}를 사용한다.
객체의 프로퍼티와 객체의 프로퍼티를 구분할때 ,를 사용한다.
객체는 key(property 또는 속성) : value로 구성된다.
value를 funcion으로 할 경우
method : fuction() {}

egoing을 불러오는 법
coworkers.programmer

객체 추가하는 법
coworkers.~~~ = "~~~";

객체를 추가할 때 띄어쓰기를 포함해서 넣고 싶다
coworkers["~~ ~~~"] = "~~";

객체를 배열로 가져오기

const data = {
	squadName: 'Super hero squad',
	homeTown: 'Metro City',
	formed: 2016,
	secretBase: 'Super tower',
	active: true,
	members: [
		{
			name: 'Molecule Man',
			age: 29,
			secretIdentity: 'Dan Jukes',
			powers: [
				'Radiation resistance',
				'Turning tiny',
				'Radiation blast',
			],
		},
		{
			name: 'Madame Uppercut',
			age: 39,
			secretIdentity: 'Jane Wilson',
			powers: [
				'Million tonne punch',
				'Damage resistance',
				'Superhuman reflexes',
			],
		},
		{
			name: 'Eternal Flame',
			age: 1000000,
			secretIdentity: 'Unknown',
			powers: [
				'Immortality',
				'Heat Immunity',
				'Inferno',
				'Teleportation',
				'Interdimensional travel',
			],
		},
	],
};

    
const keys = Object.keys(data);
const values = Object.values(data);
const entries = Object.entries(data);

Object.keys()

console.log(keys);  // [
  'squadName',
  'homeTown',
  'formed',
  'secretBase',
  'active',
  'members'
]

Object.values()

console.log(values);  
//  [
  'Super hero squad',
  'Metro City',
  2016,
  'Super tower',
  true,
  [
    {
      name: 'Molecule Man',
      age: 29,
      secretIdentity: 'Dan Jukes',
      powers: [Array]
    },
    {
      name: 'Madame Uppercut',
      age: 39,
      secretIdentity: 'Jane Wilson',
      powers: [Array]
    },
    {
      name: 'Eternal Flame',
      age: 1000000,
      secretIdentity: 'Unknown',
      powers: [Array]
    }
  ]
]

Object.entries()

console.log(entries);
//
[
  [ 'squadName', 'Super hero squad' ],
  [ 'homeTown', 'Metro City' ],
  [ 'formed', 2016 ],
  [ 'secretBase', 'Super tower' ],
  [ 'active', true ],
  [ 'members', [ [Object], [Object], [Object] ] ]
]

객체의 열거 (반복문 활용)

for in을 사용한다.

for(var key in coworkers){
document.write(key+'<br>');
}

을 쓴다면 모든 key값을 가져온다.
ex) programmer, designer, bookkeeper data...

for(var key in coworkers){
document.write(coworkers[key]+'<br>');
}

를 쓴다면 egoing, leezche, buru, taeho 를 가져온다.

고로

for(var key in coworkers){
document.write(key +' : '+coworkers[key]+'<br>');
}

를 쓰면 모든 정보를 가져올 수 있다.

객체안에 소속된 함수를 메소드라 칭하고,
객체안에 속한 변수를 프로퍼티라고 한다.

obj.hasOwnProperty()

자신의 고유 속성 즉 상속받은 프로퍼티가 아닌 순수 자신의 속성인 경우에만 true라는 값을 반환하는 특징이 있습니다.

엄밀히 말하면 hasOwnProperty() 를 사용하지 않았다고 해서 에러가 발생하지는 않습니다.

작업 내용에 따라, 또 개발자가 코드에 확신을 가지고 있다면 hasOwnProperty() 를 사용하지 않아도 되며, 이 경우 루프 속도도 약간 개선됩니다.

그러나 객체와 객체 프로토타입 체인의 내용을 보장할 수 없다면, 그냥 hasOwnProperty() 확인을 추가하는 편이 좀더 안전할 것입니다.

메소드를 사용하여 모든 값 가져오기

showAll : coworkers의 모든 객체들을 불러오는 코드

이렇게 쓸 경우, 앞서 쓴 coworkers(객체)의 이름이 바뀌면 실행이 안될 수 있다.

때문에,
showAll이라는 함수 안에서 객체를 가르키는 약속된 기호인 this로 바꿔 주면 된다.

JS 버전

객체 안의 객체 활용

profile
취미로 하는 공부기록장

0개의 댓글