JS - object (객체)

소밍·2022년 3월 1일
0

Javascript

목록 보기
7/11
post-thumbnail

1. literals and properties

object = { key : value }

오브젝트는 key와 value의 집합체

2. computed properties

(키는 항상 string 타입으로 작성해야함!)

console.log(ellie.name);
console.log(ellie['name']);

우리가 .을 쓸 땐 코딩하는 그 순간 key에 해당하는 값을 받아오고 싶을 때
computed properties 쓸 땐 우리가 정확하게 어떤 키가 필요한지 모를 때, 즉 런타임에서 결정될 때 사용
기본적으로 .쓰는 것이 맞음
실시간으로 원하는 키의 값을 받아오고 싶다면 computed properties쓰면 됨 (동적으로 키의 관련된 밸류를 받아올 때 유용)

3. property value shorthand

const person1 = {name:'bob', age:2};
const person2 = {name:'steve', age:3};
const person3 = {name:'dave', age:4};
const person4 = makePerson('ellie', 30);
console.log(person4);

function makePerson(name,age){
  return { 
    name,
    age,
    // 키와 밸류의 이름이 동일하다면 생략가능 
    // name : name, -> name,
    // age : age, -> age,
  };
}

오브젝트를 필요할 때 일일이 만들게 되면 불가피하게 동일한 키와 밸류들을 반복해서 작성해야하는 문제점 발생. 때문에 함수를 이용해서 값만 전달해주면 오브젝트를 만드는 유용한 함수를 만듦. class같은 함수! 즉 template같은 함수를 만듦
다른 계산을 하지않고 순수하게 오브젝트를 생성하는 함수는 대문자로 시작하게 함수를 만들고

4. constructor function

const person1 = {name:'bob', age:2};
const person2 = {name:'steve', age:3};
const person3 = {name:'dave', age:4};
const person4 = new Person('ellie', 30);
console.log(person4);

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

5. in operator

해당하는 오브젝트 안에 키가 있는지 없는지 확인하는 것

//name이라는 key가 ellie안에 있는지 확인하는 방법 
console.log('name' in ellie); // 있으면 true
console.log('random' in ellie); // 없으면 false

//정의하지 않은 key를 접근하게 되면?
console.log(ellie.random); // undefined 나옴 

6. for..in vs for..of

//for (key in object)
console.clear();
for(key in ellie){
  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]);
}

> 더 효과적으로 작성하는 방법 
const array = [1,2,4,5];
for (value of array){
  console.log(value);
}

7. cloning

const user = {name: 'ellie', age:'20'};
const user2 = user;
user2.name = 'coder';
console.log(user); // {name:"coder", age:"20"}

이렇게 되지 않고 오브젝트 복제하는 방법! 
//1) old way
const user3 = {};
  user3[key] = user[key];
}
console.clear();
console.log(user3); // {name:"ellie", age:"age"}
//유저 안에 있는 코드를 빙글빙글 돌면서 첫번째 키는 name, 두번째 키는 age


//2) object에 있는 assign 쓰기 
//object는 자바스크립트에 기본적으로 탑재되어있는 오브젝트 중 하나 
//자바스크립트에 있는 모든 오브젝트는 오브젝트를 상속함. 
const user4 = {};
object.assign(user4, user);
//복사하고자 하는 타겟과 복사하려고하는 소스를 같이 전달 
console.log(user);//{name:"ellie", age:"age"}

//another example
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개의 댓글