본문 바로가기

Frontend/자바스크립트 Java Script

[ES6] 전개 연산자 ...Array / [...배열이름] / ...Object

...array1 하면 array1배열 안의 모든 요소들을 나열하는 형태

 

var array1 = ['one', 'two'];

var array2 = ['three', 'four'];

 

var combined = array1.concat(array2);  // concat으로 배열array 합치기

console.log(combined)        -> ['one', 'two', 'three', 'four']   

(합쳐진 새로운 배열 생김. 기존배열은 그대로 유지됨)  

 

이걸 전개 연산자로 바꾸면

var combined = [array1, array2];

console.log(combined);       ->[ ['one', 'two'], ['three', 'four'] ] 어레이 안에 어레이가 들어감

 

요소를 나열해서 하나의 배열로 합치려면 ...배열이름사용

var combined = [...array1, ...array2];

console.log(combined);       ->  ['one', 'two', 'three', 'four']   

 

배열에 요소 나열하는 중간에도 전개연산자... 사용 가능

var combined = ['zero', ...array2, 'add', ...array1];

console.log(combined);      -> ['zero', 'three', 'four', 'add', 'one', 'two'];

 

인덱스로 해당 위치의 항목을 추출하는 데에도 사용 가능

var first = array1[0];

var second = array1[1];

console.log(first, second);    -> one two

 

var [first, second] = array1;  // 변수 선언 시 array1과 동일한 데이터 타입인 배열표시 [ ]를 하고 그 안에 해당하는 위치에 변수명을 적으면, first, second이름의 변수를 자동으로 선언하고 array에서 같은 위치 즉, 첫번째, 두번째에 해당하는 변수가 할당됨.

 

var array1 = ['one', 'two', 3, 4, 5]

var [first, second, ...other] = array1

console.log(first, second, other);      -> one 'two' [ 3, 4, 5 ]

이 때, 전개연산자 ... 를 사용하면 other이라는 이름의 변수를 생성하고 추출된 요소 외에 남은 요소들이 할당되어 배열 형태로 들어감.

 

이런 추출 방식은 함수에서도 동일하게 사용 가능함.

기존에 함수의 특정 항목을 모르면서 추출하고자 할 때는 arguments라는 특수변수를 사용했음.

function func() {

    console.log(arguments);  ->[Arguments] { '0': 1, '2': 2, '2': 3 }

}

func(1, 2, 3);      

 

그래서 배열로 추출해 담으려면 Array의 내장함수를 사용함.

function func() {

    var args = Array.prototype.slice.call(arguments);

    console.log(args[0]);            ->1

    console.log(args.slice(1));      ->[2, 3] 

}

func(1, 2, 3); 

 

이를 동일하게 사용할 수 있는 것이 전개연산자 ...

function func(...args) {

    console.log(args[0]);            ->1

    console.log(args.slice(1));      ->[2, 3] 

}

func(1, 2, 3); 

 

첫번째 항목 지정해 먼저 할당하고 나머지 전개연산자로 사용가능

function func(first, ...args) {

    console.log(first);                ->1

    console.log(args);                ->[2, 3] 

}

func(1, 2, 3); 

 

단, 중간에 넣어 추출하는 방식은 사용 불가. 항상 마지막에 넣어 사용해야 함.

function func(first, ...args, last) {

    console.log(first);                ->1

    console.log(args);                ->[2, 3] 

}

func(1, 2, 3); 

 

객체(Object)에도 사용가능

var object1 = { one: 1, two: 2, other: 0 };

var object2 = { three: 3, four: 4 };

var combinedObj = { ...object1, ...object2 };

console.log(combinedObj)   -> { one: 1, two: 2, other: 0, three: 3, four: 4 }

 

오브젝트의 경우 키값이 같아 충돌될 수 있음. 이 경우 뒤에 있는 값이 앞에 있는 값을 덮어쓴다.

var object1 = { one: 1, two: 2, other: 0 };

var object2 = { three: 3, four: 4, other: -1 };

var combinedObj = { ...object1, ...object2 };

console.log(combinedObj)   -> { one: 1, two: 2, other: -1, three: 3, four: 4 }

 

객체에서는 똑같이 객체표현식 {}을 쓰고 같은 키값을 쓰면 해당하는 키값이 선언된 후 추출된다.

키 값을 동일하게 선언할 경우에만 값이 추출된다.

var { one } = object1;

console.log(one);         ->1

 

추출된 값을 다른 변수로 선언하고 싶을 때는 : 을 사용

var { one: myOne } = object1;

console.log(myOne);    ->1

오브젝트 안에 오브젝트가 들어 있을 경우에도 키값을 통해 오브젝트를 추출 가능

var object1 = { one: 1, two: 2, other: 0 };

var object2 = { three: 3, four: 4, other: -1 , obj: object1 };

var { obj: myObj } = object2;

console.log(myObj);     -> { one: 1, two: 2, other:0 }

 

오브젝트 안의 오브젝트의 값(밸류)을 키를 통해 추출할 때,

var { obj: { two } } = object2;

console.log(two);    -> 2

console.log(obj);      -> obj is not defined. obj라는 변수를 생성하는게 아니라 키를 참조한다는 뜻으로만 사용된 것.

 

똑같이 키 대신 새로운 변수이름 할당 후 추출 가능

var { obj: { two: myTwo } } = object2;

console.log(myTwo);    -> 2

 

'Frontend > 자바스크립트 Java Script' 카테고리의 다른 글

[자바스크립트] Class -객체지향언어  (0) 2020.11.03
[자바스크립트] Object  (0) 2020.11.03
Array의 push, concat 차이  (0) 2020.10.26
React 설치  (0) 2020.09.28
Promise 비동기처리  (0) 2020.08.18