[자바스크립트 기초] Object와 Property, Cloning

·2022년 2월 15일
0

Java Script

목록 보기
5/8
post-thumbnail

드림코딩 자바스크립트 기초 강의를 들으며 학습한 내용을 정리해보았다.
⭐️ 재생목록 바로가기

1️⃣ Object

  • object는 데이터를 효율적으로 관리하기 위해 사용한다.
  • 오브젝트는 키와 값의 집합체이다!
    object = { key : value }

<오브젝트 만드는 방법>
1. Curly bracket -> object literal snytax
2. Class 생성자 함수 -> object constructor snytax

const obj1 = {};//object literal snytax
const obj2 = new Object();//object constructor snytax

자바스크립트는 동적으로 타입이 런타임(프로그램이 동작하고 있을 때) 결정되는 언어이므로, 객체의 속성을 자유롭게 추가,삭제 및 수정 가능하다.

function print(person){
    console.log(person.name);
    console.log(person.age);
}//literal properties

const Franky = {
    name: 'Franky',
    age: 29,
}//Franky라는 객체 생성
print(Franky)

Franky.job = 'engineer';//속성과 값 추가

2️⃣ Computed properties

  • 오브젝트의 속성값 불러오는 방법 -> 배열의 값 받아오는 것처럼 접근
    이 때 key는 따옴표를 써서 string으로!
console.log(Franky['name']);//Computed properties

Franky['hasjob'] = true;//literal properties와 같이 속성과 값 추가, 삭제 및 수정 가능

console.log(Franky);//결과 : {name: 'Franky', age: 29, job: 'engineer', hasjob: true}

💡 여기서 잠깐!
Q. literal properties(닷)과 computed properties, 언제 써야할까?

A. 일반적으로 코딩하는 경우 ➔ literal properties

그러나 input을 통해 사용자가 입력하는 값을 받아와야 하는 등 runtime(프로로그램이 동작할 때)때 값이 결정되는 경우
➔ computed properties
즉, 동적으로 key의 값을 받아와야 할 때 유용하게 쓰임

const printValue= (obj,key) => {
    console.log(obj.key)
}

printValue(Franky, 'name');

➔ literal properties의 경우, undefined(속성 key의 값이 정의되지 않은 상태)

const printValue= (obj,key) => {
    console.log(obj[key])
}

printValue(Franky, 'name');//Franky
printValue(Franky, 'age');//29

3️⃣ for..in vs for..of

  • for..in
    for (key in obj)
    객체의 키 값을 가져온다.
for (let key in Franky){
    console.log(key);
}

➔ 출력 결과

  • for...of
    for (value of iterable)
    배열, string, map 과 같은 iterable한 데이터타입의 값을 가져온다.
const arr = [1, 2, 5, 6];
for (let value of arr ){
    console.log(value);
}

➔ 출력 결과

4️⃣ Cloning

  • Object.assign 메서드를 통해 객체 복제가 가능하다.
    object.assign(dest, [obj1, obj2, obj3...])

  • target 객체(복제하고자 하는 객체)와 source 객체(복제할 객체)를 파라미터로 받음
    -> 리턴 값은 target & source

const user = {name: 'Min', age: '30'};

const user2 = {};// 빈 객체로 만들어 두고 복제
Object.assign(user2, user)//target, source
console.log(user2);//{name: 'Min', age: '30'}

const user3 = Object.assign({}, user)
console.log(user3);//{name: 'Min', age: '30'}

//another example(source가 여러 개일때)
const fruit1 = { color : 'red'};
const fruit2 = { color : 'blue', size: 'big'};
const mixed = Object.assign({}, fruit1, fruit2);
console.log(mixed.color);//blue -> 값 덮어씌워짐
console.log(mixed.size);//big
profile
걸음마 개발 분투기

0개의 댓글