js

[javascript] object 정리

beaksul 2022. 8. 26. 18:55

1. Literals & properties

 

object = {key : value};

object는 key와 value의 집합체

key = 변수(properties)

value = 변수의 값

// object 생성 방법
const obj1 = {}; // object literal
const obj2 = new Object(); // object constructor

const jiwon = {name : 'hi', age: 7}
// class 없이 바로 object 생성 가능

jiwon.job = true;
// 뒤늦게 프로퍼티 생성 가능
// 유지보수에 좋지 않음

delete jiwon.job;
// 삭제 가능

 

 

 

2. Computed properties

console.log(jiwon.name);
// 정확히 필요한 키가 있을 때
console.log(jiwon['name']);
// 어떤 키를 가져와야하는 지 모를 때, 동적으로 받아와야 하는 경우

// 동일한 값을 출력
// key는 항상 string 타입으로 지정해서 받아와야 함


jiwon['job'] = true;
// 프로퍼티 추가로 생성 가능

function printValue(obj, key){
	console.log(obj[key]);
}
// 어떤 키를 가져와야하는 지 모를 때(사용자에게 입력 받을 때)

printValue(jiwon, 'name');
printValue(jiwon, 'key');

 

 

 

3. Constructor Function

// object를 일일히 다 만들게 되면 동일한 key와 value를 반복해서 적어야하는 불편함이 있음

function Person(name, age){
	// this = {};
	this.name = name;
    this.age = age;
    // return this;
}

// 호출 시
const person = new Person('jiwon', 7);

 

 

 

4. in operator

 

object안에 key가 있는지 확인

console.log('name' in jiwon); // true
console.log('age' in jiwon); // true
console.log('random' in jiwon); // false
console.log(jiwon.random); // 정의 되지 않은 값 undefined

 

 

 

5. for..in vs for..of

console.clear();

// for (key in obj)
for (key in jiwon){
	console.log(key);
}

// for (value of iterable)
const array = [1, 2, 4, 5]

for (let i = 0; i < array.length; i++){
	console.log(array[i]);
}
// 결과 값 : 1 2 4 5
// 긴 코드를 간단하게!

for (value of array){
	console.log(value);
}
// array에 있는 모든 값들이 value에 할당되면서 출력됨

 

 

 

6. Fun cloning

const user = {name: 'jiwon', age: '7'};
const user2 = user;
user2.name = 'coder';
console.log(user);
// user의 name이 coder로 변경됨

// 복사
// old way
const user3 = {};
for (key in user){
	user3[key] = user[key];
}
// for in을 이용하여 user의 key값과 user3의 key값을 동일하게 복사함
// user3[name] = user[name];
// user3[age] = user[age];

const user4 = {};
Object.assign(user4, user);
// 자바스크립트에 있는 기본적인 Object
// assign = assign<T, U>(target: T, source: U): T & U;
// 복사하고자 하는 타겟과 소스를 전달해줘야하고, 리턴 값은 두가지가 혼합됨
// 같은 소스에 여러가지가 있을 경우 나중에 써진 소스로 덮어씌워짐

const user4 = Object.assign({}, user);
// 두가지 동일한 결과 값