구조 분해와 할당 js

이종원·2020년 10월 24일
0

배열을 분해하다

const arr = ['hi', 'my', 'name', 'is']

const [first, second] = arr

first // 'hi'

second // 'my'

const result = []
function foo([first, second]){
  result.push(second)
  result.push(first)
}

foo(arr) // undefined
result // ["states", "code"]

rest/spread 문법을 배열 분해에 적용

const arr = ['you', 'and', 'i', 'we']
const [start, ...rest] = arr

start // 'you'
rest // ['and', 'i', 'we']

객체의 단축(shorthand) 문법

const name = '박춘삼'
const age = '65'

const inform {
  name,
  age,
  job: '어부'
}

 inform // {name: '박춘삼', age:'65', job:'어부'}
 inform.name // '박춘삼'
 inform.age // '65'
 inform.job // '어부'

객체를 분해

const player = {name: '김덕배', team: '맨시티'}
const { name } = player
const { team } = player

name // '김덕배'
team // '맨시티'

rest/spread 문법을 객체 분해 및 적용

#1

const car = {brand: '롤스로이스', model: '고스트'}
const { brand, ...args } = car

name // '롤스로이스'
args // {model: '고스트'}
#2

const car = {brand: '람보르기니', model: '우루스', type: '대형 SUV', price: '약 3억'}

function buyTheNewCar({brand, model: name, price}){
	return `${price}을 주고 ${brand} ${name}을 샀다`
}

buyTheNewCar(car) // "약 3억을 주고 람보르기니 우르스을 샀다"
#3

const user = {
  name: '이봉수',
  company: {
    name: '하이컴퍼니',
    department: 'marketing',
    role: {
      name: 'growth hacker'
    }
  },
  age: 25
}
--------------------------

const changeUser = {
  ...user, // 위에 있는경우 내용에 변화가 생김
  name: '최고순',
  age: '54' 
}

changeUser.name // '최고순'
changeUser.age // '54'

--------------------------

const overwriteChanges = {
  name: '최고순',
  age: '54',
  ...user // 아래에 있는 경우 내용의 변화가 안 생김
}

overwriteChanges.name // '이봉수'
overwriteChanges.age // '25'

--------------------------

const changedDepartment = {
  ...user,
  company: {
    ...user.company,
    department: 'Development'
  }
}

changedDepartment.company.department // 'Development'
changedDepartment // {
      name: '이봉수',
      company: {
        name: '하이컴퍼니',
        department: 'Development',
        role: {
          name: 'growth hacker'
        }
      },
      age: 25
    }

0개의 댓글