JavaScript에서 전개구문이라하고, 무언가 펼치는 행위를 한다 라고 이해하면 좋겠다.
spread syntax가 사용되는 예
//함수 호출 myFunction(...iterableObj); //배열 리터럴과 문자열 [...iterableObj, '4', 'five', 6]; //객체 리터럴 let objClone = { ...obj };
printName이라는 함수를 호출할 시 인자를 spread syntax를 사용하여 배열 내 요소를 하나씩 인자로 전달 할 수 있다.
형태는
let studentsName = ['john','lora','micheal'];
function printName(firstStudent, secondeStudent, thirdStudent){
console.log(`제 이름은 ${firstStudent} 입니다.`);
console.log(`제 이름은 ${secondeStudent} 입니다.`);
console.log(`제 이름은 ${thirdStudent} 입니다.`);
}
printName(...studentsName);// = printName('john','lora','micheal');와 같다.
// 제 이름은 john 입니다.
// 제 이름은 lora 입니다.
// 제 이름은 micheal 입니다.
배열의 병합이라고 봐도 무방할 정도의 간결한 문법을 가진다.
let studentsName = ['john','lora','micheal'];
let addedStudentsName = [...studentsName, 'sam', 'bora'];
console.log(addedStudentsName);
//['john', 'lora', 'micheal', 'sam', 'bora']
/*-------------------------------------------------------*/
let arrayA = [0,1,2];
let arrayB = [2,4,5];
arrayA = [...arrayA, ...arrayB];
console.log(arrayA);
//[0, 1, 2, 2, 4, 5]
배열과 비슷하게 병합되지만 다른점은 key값이 중복되는 경우 덮어쓰기를 한다는 점이다.
var man = { name: 'john', age: 42, hobby:"soccer" }
var women = { name: 'lora', age: 13 , hobby: "sketch"};
var clonedObj = { ...man };
console.log(clonedObj);
//{name: 'john', age: 42, hobby: 'soccer'}
var mergedObj = { ...man, ...women };
console.log(mergedObj);
//{name: 'lora', age: 13, hobby: 'sketch'}
!!!spread syntax는 iterable 객체에만 적용된다.
//spread syntax인 ...obj는 요소를 하나만 가지고있다.
var obj = {'key1': 'value1'};
var array = [...obj];
console.log(array)
//Uncaught TypeError: object is not iterable
참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
명사 (일정하게 정한) 한도
수학 : 매개변수
rest의 나머지, parameter는 매개변수 즉 나머지 매개변수?? 어렵습니다.
MDN에서는 정해지지않은 수(an indefinte number, 부정수) 인수를 배열로 나타낼 수 있게 한다 라고 합니다.
다시말해, 함수의 parameter의 수를 정하지 않고 몇가지가 들어오더라도 나머지의 parameter를 배열의 형태로 사용하겠다 입니다.
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// Console Output:
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]
참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters