[TIL] spread와 rest 차이

oaksusu·2024년 5월 11일
0

TIL

목록 보기
32/36
post-thumbnail

1. spread

: 압축되어 있는 값을 풀어준다.

1-1. 객체

const sunjae = {
	name: '선재'
} ;

const student = {
	...sunjae,
    age: 19 
}

const tallestStudent = {
	...student,
    height: 189
}

1-2. 배열

const AToF = ['a', 'b', 'c', 'd', 'e', 'f']; 
const AToI = [...AToF, 'g', 'h', 'i']; // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

const code = ['a', 'b', 'c', 'd', 'e', 'f'];
const mixed = [...code, 1000, ...code] ; // ['a', 'b', 'c', 'd', 'e', 'f', 1000, 'a', 'b', 'c', 'd', 'e', 'f']

1-3. 함수의 인자

const nums = [10, 2000,30];

function sum(a,b,c) {
	return a + b + c;
}

sum(...nums); 

2. rest

: 여러개의 값을 하나로 압축시킴

2-1. 객체

const tallestStudent = {
	name: '선재',
    age: 19,
    height: 189
}

const {height, ...student} = tallestStudent;
console.log(height); // 189
console.log(student); // {name: '선재', age: 19}

2-2. 배열

: 단, 배열에서는 rest를 먼저 쓸수 없고 마지막에 써야함!

const code = ['a', 'b', 'c', 'd', 'e', 'f'];

const [first, ...rest] = code;
console.log(first); // 'a'
console.log(rest); // ['b', 'c', 'd', 'e', 'f']

const [...rest, last] = code; // ------------> 이건 안됨

2-3. 함수 매개변수

: 모든 요소들을 배열로 모음

function calculate(type, ...numbers) {
	let total = 0;
    numbers.forEach(ele => {
    	if (type === 'plus') {
			total += ele;
		} else {
        	total -= ele;
        }
	})
    return total;
} 

calculate('plus', 10, 2000, 30, 2022); 
calculate('minus', 10, 2000, 30); 

참고

스프레드와 rest문법
[JavaScript]rest와 spread 차이

profile
삐약

0개의 댓글