Rest Parameter And Spread Operator
JavaScript는 ES6에서 Rest Parameter와 Spread Operator를 도입하여 함수와 배열을 더 유연하고 간결하게 처리했습니다. 이러한 연산자는 동일한 구문(…)을 사용하지만 서로 다른 목적을 갖습니다. Rest Parameter는 여러 값을 배열로 수집하는 반면 Spread Operator는 배열이나 객체에서 요소를 펼칩니다. 참조
Rest parameter
- Rest Parameter는 함수가 무한한 수의 인수를 배열로 허용할 수 있도록 합니다. 여러 인수를 단일 배열 매개변수로 수집합니다..
function passRestParam(a, b, ...args) {
// a: 1, b: 2, ...args: [3, 4, 5] <-- 배열로 인자값을 출력합니다.
}
passRestParam(1, 2, 3, 4, 5);
function passRestParam(a, ...args, b) {
// syntaxError: Rest parameter must be last formal parameter
// Rest parameter는 마지막 매개변수여야 합니다.
}
Rest parameter 를 실전에 적용하기
1. filtering
Object 안의 property를 필터링한다.
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(a) // 1
console.log(rest) // { b: 2, c: 3 }
2. 배열의 재구성
const [first, ...rest] = [1, 2, 3, 4];
console.log(first) // 1
console.log(rest) // [ 2, 3, 4 ]
3. default parameters 기능
function mul(factor, ...nums) {
return nums.map(num => num * factor);
}
console.log(mul(2,1,2,3,4,5)) // [ 2, 4, 6, 8, 10 ]
Spread operator
JavaScript의 스프레드 연산자(…arr)는 배열이나 객체를 개별 요소로 확장하는 데 사용됩니다. 이를 통해 함수 호출에서 배열의 요소를 별도의 인수로 쉽게 전달하거나 여러 배열을 하나로 결합할 수 있습니다. 스프레드 연산자는 배열이나 객체로 작업할 때 코드를 더 간결하고 읽기 쉽게 만드는 데 도움이 됩니다.
const n = [1, 2, 3];
const ne = [...n, 4, 5];
console.log(ne); // [ 1, 2, 3, 4, 5 ]
Spread operator 를 실전에 적용하기
1. Merging Arrays
const a1 = [1, 2];
const a2 = [3, 4];
const merged = [...a1, ...a2];
console.log(merged) // [ 1, 2, 3, 4 ]
2. Cloning Arrays
원 배열의 shallow copy 를 제공한다. 새로운 배열은 원배열로부터 독립적이다.
const original = [10, 20, 30];
const clone = [...original];
console.log(clone)
3. Combining Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const combined = { ...obj1, ...obj2 };
console.log(combined) // { a: 1, b: 3, c: 4 }
기타 다양한 예시
let array = [3, 4, 5]
let newArray = [...array]; // [3, 4, 5] //
array.push(...[6, 7]); // [3, 4, 5, 6, 7]
array.unshift(...[1, 2]); // [1, 2, 3, 4, 5, 6, 7]
let arr1 = [1, 2];
let arr2 = [6, 7];
let arr3 = [...arr1, 3, arr2]; // [1, 2, 3, 6, 7]
arr3.splice(3, 0, ...[4, 5]); // [1, 2, 3, 4, 5, 6, 7]
console.log(1, 2, 3); // 1 2 3
let arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]
console.log(...arr); // 1 2 3
Math.max(1, 2, 3); // 3
let arr = [1, 2, 3];
Math.max(arr); // NaN
Math.max.apply(null, arr); // Math.max(1, 2, 3) -> 3
Math.max(...arr); // Math.max(1, 2, 3) -> 3
let array1 = new Array(1, 2, 3); // [1, 2, 3]
let array2 = new Array.apply(arr); // Uncaught TypeError: Array.apply is not a constructor
let array3 = new Array(...arr); // [1, 2, 3]
let parts = ['shoulders', 'knees']
let lyrics = ['head', ...parts, 'and', 'toes']
console.log(lyrics) // output: ["head", "shoulders", "knees", "and", "toes"]
let obj = {a: 1,b: 2, x: 3,y: 4}
let {a, b, ...c} = obj;
console.log(a, b, c); // 1 2 {x: 3, y: 4}
let newObj = {a, b, ...c};
console.log(newObj); // {a: 1, b: 2, x: 3, y: 4}