spread syntax
는 iterable한 모든 것의(대표적으로 문자열, 배열)요소를 "펼쳐"주는 문법을 의미합니다.const spread = [1, 2, 3];
const arr = [0, ...spread, 4];
console.log(arr); // [0, 1, 2, 3, 4]
const spread = [];
const arr = [0, ...spread, 1];
console.log(arr); // [0, 1]
const arr1 = [0, 1, 2];
const arr2= [3, 4, 5];
const concatenated = [...arr1, ...arr2]
console.log(concatenated); // [0, 1, 2, 3, 4, 5]
const person1 = {
name: 'han',
age: 30
}
const person2 = {
hobby: 'golf',
job: 'programmer'
}
const user = {...person1, ...person2};
console.log(user)
// {name: 'han', age: 30, hobby: 'golf', job: 'programmer'}
const arr = [1, 2, 3];
const copiedArr = [...arr]
copiedArr.pop(0)
console.log(arr); // [1, 2, 3]
console.log(copiedArr); // [1, 2]
위 예제에서처럼 전개(spread)문법이 깊은 복사처럼 보이지만 아래 예제처럼 중첩된 구조에 대한 깊은 복사는 이뤄지지 않습니다.
const arr = [1, 2, [3,4]];
const copiedArr =[...arr]
copiedArr[2].pop(0);
console.log(arr); // [1, 2, [3]]
console.log(copiedArr); // [1, 2, [3]]
...manyMoreArgs
는 rest parameter, rest syntax라고 부릅니다. 남아있는 모든 인자를 하나의 배열에 담기 때문입니다.function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// 콘솔 출력:
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]
function sum(...nums){
let sum = 0;
for(let i = 0; i < nums.length; i++){
sum = sum + nums[i];
}
return sum;
}
console.log(sum(1, 2, 3)) // 6
console.log(sum(1, 2, 3, 4)) // 10
function getAllParams(required1, required2, ...args){
return [required1, required2, args];
}
console.log(getAllParams(123)) // [123, undefined, []]
arguments 객체
는 함수에 전달된 인수에 해당하는 Array 형태의 객체입니다.function getAllParamsByRestParameter(...args){
return args;
}
function getAllParamsByArgumentObj(){
return arguments;
}
const restParams = getAllParamsByRestParameter("first", "second", "third");
const argumentsObj = getAllParamsByArgumentObj("first", "second", "third");
console.log(restParams); // ["first", "second", "third"]
console.log(argumentsObj) // ["first", "second", "third"]
// rest 문법은 배열을 반환하지만 arguments 객체는 유사 배열 객체를 반환합니다.
console.log(Array.isArray(restParams)) // true
console.log(Array.isArray(argumentsObj)) // false
구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 담을 수 있게 하는 Javascript 표현식입니다.
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]