JavsScript spread syntax, rest parameter

CodeLog·2020년 11월 25일
0

spread syntax

사전적의미 (참조 네이버사전)

spread

  1. 동사 (접혀 있던 것을) 펼치다[펴다]
  2. 동사 (잘 보이도록) 펼치다[펴다]
  3. 명사 확산, 전파 (→middle-age spread)
  4. 명사 다양성, 폭넓음

syntax

  1. 명사 언어 구문론, 통사론 (→morphology)
  2. 명사 컴퓨터 (컴퓨터 언어의) 문법

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

사전적의미 (참조 네이버사전)

spread

  1. 명사 (어떤 것의) 나머지
  2. 명사 나머지 (사람들·것들), 다른 사람들[것들]
  3. 동사 쉬다, 휴식을 취하다, 자다; (몸의 피로한 부분을 편하게) 쉬다 (→rested)

parameter

명사 (일정하게 정한) 한도
수학 : 매개변수

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

profile
개발로그

0개의 댓글