본문 바로가기
JAVASCRIPT

[Spread syntax] 데이터 원본 보존하기, shallow copy (예제 포함)

by sjs_2215 2020. 4. 16.

spread문법을 사용하여 shallow copy 하는 방법에 대해 소개

 

shallow copy - 원본을 복사하는 방법 중 하나이다.

 

[...객체이름] -> ...라는 문법을 사용하여 복사하면 된다.

 

 

사용법 예시)

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

numbers2 =[2,3,3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

 


 

sorting 하기 전으로 되돌리는 함수 만들어보기 (Vue.js)

-> 원본 배열을 복사해두는 방법을 사용할 것! 

 

data 부분.

원본 배열을 복사해둔다.

  data() {
    return {
      Oneroom: Oneroom,
      Oneroom원본: [...Oneroom],
    };
  },

 

sortOriginal 메소드에서 this.배열 = 복사해둔원본배열 을 넣어준다.

  methods:{
    sortPrice(){
      this.Oneroom.sort(function(a,b){
        return a.price-b.price
      });
    },
    sortOriginal(){
      this.Oneroom = [...this.Oneroom원본];
    },
  }

 

 


 

shallow copy와 deep copy의 특징/차이점 설명 참고

: https://brunch.co.kr/@kd4/87

 

Comments