배열이랑 객체의 차이를 모르고 있었다... 정확히는 객체가 뭔지 몰랐던 것 같다.

 

객체는 key와 그 key에 따른 value를 저장할 수 있는 구조 혹은 하나의 집합을 말한다. 만약 나를 하나의 객체로 보고 예시를 들자면

 

 - 이름 : 신승준

 - 나이 : 27

 - 고향 : Busan

 - 현 직장 : Samsung

 - Github ID : DelightJun

 

위와 같은 나라는 객체를 각각의 분류로 나누고 그 분류에 값을 넣어 표현하는 것이 key와 value로 이루어진 객체라고 볼 수 있겠다.

 

이를 JavaScript로 나타내면 다음과 같을 것이다.

var me = {
	name : 'SeungJun Shin',
	age : 27,
	hometown : 'Busan',
	workplace : 'Samsung',
	GithubID : 'DelightJun'
};

console.log(me); // {name: 'SeungJun Shin', age: 27, hometown: 'Busan', workplace: 'Samsung', GithubID: 'DelightJun'}

배열은 [과 ]으로 표현되지만 객체는 {와 }으로 표현되며 key와 value가 존재한다.

 

  • 접근

우리는 다음과 같은 방법으로 객체 안의 value에 접근할 수 있다.

var me = {
	name : 'SeungJun Shin',
	age : 27,
	hometown : 'Busan',
	workplace : 'Samsung',
	GithubID : 'DelightJun'
};

console.log(me);

var myName = me.name;
var myAge = me.age;
var myHometown = me['hometown'];

console.log(myName, myAge, myHometown); // 'SeungJun Shin' 27 'Busan'

 

  • 객체에 정보 혹은 key/value 혹은 Data 추가
var me = {
	name : 'SeungJun Shin',
	age : 27,
	hometown : 'Busan',
	workplace : 'Samsung',
	GithubID : 'DelightJun'
};

me.future = 'developer';
me['country'] = 'Korea';

console.log(me);

 

  • 객체 정보 수정
var me = {
	name : 'SeungJun Shin',
	age : 27,
	hometown : 'Busan',
	workplace : 'Samsung',
	GithubID : 'DelightJun'
};

me.age = 28;
me['workplace'] = 'I dont know';

console.log(me);

 

  • 객체 정보 삭제
var me = {
	name : 'SeungJun Shin',
	age : 27,
	hometown : 'Busan',
	workplace : 'Samsung',
	GithubID : 'DelightJun'
};

delete me.workplace;

console.log(me);

 

  • 객체 순회
const sample = {
	one : 1,
	two : 2,
	three : 3
};

for (let i in sample) {
	console.log(i);
	console.log(sample[i]);
}

for문을 사용해 객체 안을 순회?할 수 있다. for로 반복문을 만들고 let i를 통해 변수를 선언한다. 그리고 in sample로 i에 sample의 각 속성(key)이 하나씩 담기게 된다.

 

 1. sample의 첫 번째 key값이 i에 담긴다. i 속성이 출력된다. i에 담긴 key의 value가 출력된다.

 2. sample의 두 번째 key값이 i에 담긴다. i 속성이 출력된다. i에 담긴 key의 value가 출력된다.

 3. sample의 세 번째 key값이 i에 담긴다. i 속성이 출력된다. i에 담긴 key의 value가 출력된다.

 

  • 변수나 함수도 value로 받을 수 있다.
const myName1 = 'Jun';

function age() {
    return 27;
}

const me1 = {
    name : myName,
    age : age(),
};

console.log(me);
const property = 'name';

const obj = {
    [property] : 'Jun'
};

console.log(obj['property']); // undefined
console.log(obj.name); // Jun

[]를 써서 다른 변수에 저장된 문자열도 속성으로 가져올 수 있다.

 

  • Bracket notation
const person = {}; // Empty

// Dot notation
person.name = 'Jun';
person.age = 26;
person.languages = ['Korean'];

console.log(person);
console.log(person.age);
console.log(person.languages);

// Bracket notation
// person.한국 나이 = 27 // Error
// console.log(person.'한국 나이'); // Error // Error
// console.log(person.['한국 나이'); // Error
person['한국 나이'] = 27;
// console.log(person.'한국 나이'); // Error
console.log(person['한국 나이']);

JavaScript에서 '한국 나이'와 같이 식별되지 않는 속성은 Bracket notation을 사용해줘야 데이터 추가 및 삭제, 접근이 가능하다. 일반적으로 Dot notation을 많이 사용하는 편이다.

 

  • 속성(key)의 값(value)로 함수(function) 또한 대입 가능하다.
const itsme = {
    greet : function () {
                return 'hello';
            }
};

person.greet; // 함수 코드 자체가 출력된다.
person.greet(); // hello

greet은 이미 function이 되었기 때문에 person.greet;을 하면 함수 코드가 출력되고, person.greet();을 하면 function이 실행되어 hello가 출력된다.

 

  • Quiz
function foo (a) {
	return a + 3;
}

const arr = [ foo(1), foo(2), foo(3), foo('a') ];

console.log(arr); // 출력값은?



// [4, 5, 6, 'a3']

 

+ Recent posts