하루에 한 문제

spread operator (펼치기연산자, 전개연산자) (ECMAScript2015) 본문

Dev/JavaScript

spread operator (펼치기연산자, 전개연산자) (ECMAScript2015)

dkwjdi 2021. 4. 29. 15:03
var birds = ['eagle', 'pigeon']
var mammals = ['rabbit', 'cat']
var animals = birds.concat('whale').concat(mammals)
console.log(animals)

const animals2 = [...birds, 'whale', ...mammals]
console.log(animals2)

위의 두 코드는 모두 같은 결과를  return 한다.

즉 concat을 사용하지 않고 ...연산자를 통해서 배열을 만들 수 있다.

 

활용

const values = [20, 10, 30, 50, 40]
console.log(20, 10, 30, 50, 40)
console.log(...values)

console.log(Math.max(20, 10, 30, 50, 40))
console.log(Math.max.apply(null, values))
console.log(Math.max(...values))

다음과 같이 최대값을 구할 때 인자들을 일일이 적어줘야 된다. 때문에 ES6 이전에는 apply를 이용해서 했지만 위에서 봤듯이 ...을 이용해서 배열을 펼칠 수 있다.

 

 

또한 iterable 한 데이터는 모두 펼칠 수 있다.

 

심지어 Set도 펼칠 수 있다.

const set = new Set();
set.add(1).add(2).add(3);
console.log(set); // {1,2,3}

console.log(...set);

 

주의사항으로는 ...으로 새로운 배열을 만들게 되면 얕은 복사가 이루어지게 된다.

 

 

출처

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax

'Dev > JavaScript' 카테고리의 다른 글

concised method (ECMAScript 2015)  (0) 2021.04.29
shorthand properties (ECMAScript 2015)  (0) 2021.04.29
rest parameter (ECMAScript 2015)  (0) 2021.04.29
default parameter (ECMAScript 2015)  (0) 2021.04.29
forEach, map, reduce  (0) 2021.04.29
Comments