본문 바로가기
챌린지/JavaScript 30일 챌린지

[JavaScript 30일 챌린지] : 14일차

by 오주현 2022. 2. 10.
반응형

<script>
    // start with strings, numbers and booleans

    // Let's say we have an array
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];

    // and we want to make a copy of it.
    const team = players;
    console.log(players, team);

    // You might think we can just do something like this:

    // however what happens when we update that array?

    // now here is the problem!

    // oh no - we have edited the original array too!

    // Why? It's because that is an array reference, not an array copy. They both point to the same array!

    // So, how do we fix this? We take a copy instead!
    const team2 = players.slice();

    // one way

    // or create a new array and concat the old one in
    const team3 = [].concat(players);

    // or use the new ES6 Spread
    const team4 = [...players];
    team4[3] = 'heeee hawww';
    console.log(team4);

    const team5 = Array.from(players);

    // now when we update it, the original one isn't changed

    // The same thing goes for objects, let's say we have a person object

    // with Objects
    const person = {
      name: 'Wes Bos',
      age: 80
    };

    // and think we make a copy:

    // how do we take a copy instead?
    const cap2 = Object.assign({}, person, { number: 99, age: 12});
    console.log(cap2);

    // We will hopefully soon see the object ...spread

    // Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.

    const wes = {
      name: 'Wes',
      age: 100,
      social: {
        twitter: '@wesbos',
        facebook: 'wesbos.developer'
      }
    };

    console.clear();
    console.log(wes);

    const dev = Object.assign({}, wes);

    const dev2 = JSON.parse(JSON.stringify(wes));

  </script>

배열 복사와 참조에 대해 공부하는 코딩이다.

 

배열 참조는 복사한 결과물을 업데이트하면 둘 다 같은 배열을 가르키고 있기 때문에 원본도 수정이 된다.

하지만 새 배열을 만들고 이전 배열을 결합하는 형식으로 복사본을 가져가면 복사본을 업데이트 해도 원본은 업데이트가 되지 않는다.

반응형

댓글