javascript note.2

wanseung2·2021년 2월 21일
2

조건문 활용

function makeSound(user){
  const tasks = {
    승완: () => {
      console.log('안녕');
    },
    호익() {
      console.log('hello')
    },
    기열: function() {
      console.log('hi');
    }
  }
  const task = tasks[user];
  if(!task){
    console.log('...?!');
    return;
  }
  task()
}
makeSound('승완') // '안녕'
makeSound('호익') // 'hello'
makeSound('기열') // 'hi'
makeSound() // '...?!'

arrow function 과 일반적인 function형을 나타내 봤습니다.

spread와 rest

spread

const bear = {
  name: '곰탱이'
};
const fatBear = {
  name: '곰탱이',
  weight: '100kg'
};
const brownFatBear = {
  name: '곰탱이',
  weight: '100kg',
  color: 'brown'
};
console.log(bear);
console.log(fatBear);
console.log(brownFatBear);

이러한 객체가 있을 경우,
spread 연산자를 사용해서 나타내 보면

const bear = {
  name: '곰탱이'
};
const fatBear = {
  ...bear,
  weight: '100kg'
};
const brownFatBear = {
  ...fatBear
  color: 'brown'
};
console.log(bear);
console.log(fatBear);
console.log(brownFatBear);

값이 같은걸 확인해 볼 수 있다.
객체가 아닌 배열에서도 사용할 수 있다.

const frontEndTeam = ['기열', '승완', '호익'];
const ProjectTeam = [...frontEndTeam, '지원'];
console.log(frontEndTeam);
console.log(ProjectTeam);

rest

rest는 생김새는 spread 랑 비슷한데, 역할은 다릅니다.
rest는 spread 연산자와 마찬가지로 객체, 배열에서 사용할 수 있습니다.
그리고 rest는 함수의 파라미터에서도 사용이 가능합니다.
예를 들어보겠습니다.

  1. 객체에서의 rest
const brownFatBear = {
  name: '곰탱이',
  weight: '100kg',
  color: 'brown'
};
const { color, ...rest } = brownFatBear;
console.log(color); // 'brown'
console.log(rest); // {name: '곰탱이', weight: '100kg'}
  1. 배열에서의 rest
const numbers = [0, 1, 2, 3, 4, 5, 6];
const [one, ...rest] = numbers;
console.log(one); // '0'
console.log(rest); // [1, 2, 3, 4, 5, 6]
  1. 함수의 파라미터에서의 rest
function sum(...rest) {
  return rest.reduce((acc, current) => acc + current, 0);
}
const result = sum(1, 2, 3, 4, 5, 6);
console.log(result); // 21
profile
"나는 내 노력을 드러내려고 하지 않았고, 그저 내 그림들이 봄날의 밝은 즐거움을 담고 있었으면 했다. 내가 얼마나 노력했는지 아무도 모르게 말이다." - 앙리 마티스

2개의 댓글

comment-user-thumbnail
2021년 2월 24일

승완님 협업하면서 블로그 까지 리스펙!

1개의 답글