[JavaScript]Object.assign(), arguments

챔수·2023년 3월 6일
0

개발 공부

목록 보기
15/100

1. Object.assign()

const obj = {
    mastermind: 'Joker',
    henchwoman: 'Harley',
    relations: ['Anarky', 'Duela Dent', 'Lucy'],
    twins: {
      'Jared Leto': 'Suicide Squad',
      'Joaquin Phoenix': 'Joker',
      'Heath Ledger': 'The Dark Knight',
      'Jack Nicholson': 'Tim Burton Batman',
    },
  };

  const copiedObj = Object.assign({}, obj);
  delete obj.twins['Jared Leto'];

expect('Jared Leto' in copiedObj.twins).to.equal(??)

obj로 선언된 객체를 Object.assign() 을 이용해 복사를 하고 원본인obj의 참조 자료형 중 하나인 twins.Jared Leto를 삭제 했을때 복사본인 copiedObj에는 twins.Jared Leto이 남아있는지 없는지에 관한 문제다.

복사가 어떤식으로 되는지에 관한 문제인데 Object.assign을 포함한 slice(), spread syntax얕은 복사가 되는 특징을 가지고 있다.

얕은복사 사용시 유의사항

얕은복사는 참조자료형을 복사하는 방법인데 사용시 유의해야될 사항으로는
참조 자료형 내부에 참조 자료형이 중첩되어 있는 경우, slice(), Object.assign(), spread syntax를 사용해도 참조 자료형 내부에 참조 자료형이 중첩된 구조는 복사할 수 없다.
중첩되어있는 참조 자료형의 경우에는 복사가 되더라도 중첩된자료에 한에서는 같은 주소값을 참조하기 때문에 복사본을 수정해도 원본이 수정되는 상황이 온다.

console.log(copiedObj.twins)
//{ 
'Joaquin Phoenix': 'Joker',
'Heath Ledger': 'The Dark Knight',
'Jack Nicholson': 'Tim Burton Batman'
}
  • 확인결과 같은주소를 참조하고있어 복사본에서도 내용이 지워진 것을 확인할 수 있다.

2.arguments

function getAllParamsByRestParameter(...args) {
    return args;
  }
  function getAllParamsByArgumentsObj() {
    return arguments;
  }

  const restParams = getAllParamsByRestParameter('first', 'second', 'third');
  const argumentsObj = getAllParamsByArgumentsObj('first', 'second', 'third');

expect(Array.isArray(restParams)).to.deep.equal(??);
expect(Array.isArray(argumentsObj)).to.deep.equal(??);

spread syntaxarguments 로 만든 값들이 배열인지 아닌지에 관한 문제다.
MDN에서의 arguments를 보면

'arguments 객체는 함수에 전달된 인수에 해당하는 Array 형태의 객체입니다.'

객체 형태로 return이 된다는 말이다.

console.log(Array.isArray(restParams)) // ture
console.log(Array.isArray(argumentsObj)) // false

console.log(typeof argumentsObj) // object

  • 배열은 아니지만 타입은 object 로 확인된다.
profile
프론트앤드 공부중인 챔수입니다.

0개의 댓글