Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 화살표함수
- 조건문
- frontend
- 비교연산자
- align-content
- for of
- justify-content
- javascript
- 함수
- 함수선언식
- properties
- for in
- 함수표현식
- if else
- 문자열
- 속성
- flex-direction
- 타입
- boolean
- typeof
- Methods
- 논리연산자
- 반복문
- ELSE
- for
- flex
- 변수
- flex-wrap
- 기초
- 프론트엔드
Archives
- Today
- Total
하얀 코딩
[JavaScript - 12] 전개 문법 (Spread syntax) 본문
정의
전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.
객체 앞에 ...을 붙여 사용합니다.
특징
1. 인자를 펼쳐서 넣는 개념입니다.
const spread = [1, 2, 3];
const arr = [0, ...spread, 4];
// [0, [1,2,3], 4] (X)
// [0, 1, 2, 3, 4] (O)
2. 빈 배열에 전개 문법을 사용할 경우, 아무것도 전달되지 않습니다.
const spread = [];
const arr = [0, ...spread, 1];
//[0,1]
3. 기존 배열을 변경하지 않습니다. 비파괴(immutable)
let fruits = ['apple', 'banana', 'grape'];
let vegetables = ['tomato', 'pumpkin'];
let copiedFruits = [...fruits];
copiedFruits.push('pineapple');
let basket = [...fruits, ...vegetables]
console.log(basket)
// ['apple', 'banana', 'grape', 'tomato', 'pumpkin']
4. 함수에서의 전개 문법은 배열로 다루어집니다. (만약 값이 없다면 빈 배열이 값으로 들어갑니다.)
function test(...args) {
return args;
}
const restParams1 = test('first', 'second', 'third'); // ['first', 'second', 'third']
const restParams2 = test() // []
5. 함수에서 전달인자의 수가 정해져 있지 않은 경우에도 유용하게 사용할 수 있습니다.
function sum(...nums) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum = sum + nums[i];
}
return sum;
}
sum(1,2) // 6
sum(1,2,3,4) // 10
6. 함수 정의에는 하나의 전개문법만 존재할 수 있습니다.
나머지 매개변수 (Rest Parameters) 반드시 함수 정의의 마지막 매개변수여야 합니다.
// Uncaught SyntaxError: Rest parameter must be last formal parameter
foo(...one, ...wrong, ...wrong)
foo(...wrong, arg2, arg3)
foo(arg1, ...wrong, arg3)
// 올바른 사용법
foo(arg1, arg2, ...correct)
응용
1. 여러 개의 배열을 이어 붙일 수 있습니다. (배열을 병합할 때는 concat 메서드를 사용해도 됩니다.)
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const concatenated = [...arr1, ...arr2];
// [0, 1, 2, 3, 4, 5]
2. 여러 개의 객체를 병합할 수 있습니다.
const fullPre = {
cohort: 7,
duration: 4,
mentor: 'white coding',
number: '10'
};
const me = {
time: '0156',
status: 'sleepy',
todos: ['coding', 'test'],
number: '32'
};
const merged = { ...fullPre, ...me };
/**
* {
cohort: 7,
duration: 4,
mentor: 'white coding',
number: '32'
time: '0156',
status: 'sleepy',
todos: ['coding', 'test'],
}
*/
'JavaScript' 카테고리의 다른 글
[JavaScript - 14] 얕은 복사(shallow copy)와 깊은 복사(deep copy) (0) | 2022.11.18 |
---|---|
[JavaScript - 13] 구조 분해 할당 (Destructing Assignment) (0) | 2022.11.15 |
[JavaScript - 11] 호이스팅(hoisting) (0) | 2022.11.11 |
[JavaScript - 10] 클로저(Closure) (0) | 2022.11.08 |
[JavaScript - 9] 스코프(Scope) (0) | 2022.11.08 |