나머지 매개변수란?
정해지지 않은 갯수의 인수를 배열로 나타낸다. 이때 마지막 매개변수만 나머지 매개변수로 설정할 수 있다.
function showName(name) {
console.log(name)
}
showName("jihyun") // "jihyun"
showName("jihyun", "yun") // "jihyun"
showName() // undefined
function showName(...name) {
console.log(name)
}
showName("jihyun") // [jihyun]
showName("jihyun", "yun") // [jihyun, yun]
showName() // []
나머지 매개변수 구문을 사용하지 않았을때는 변수를 하나만 전달받았지만 나머지 매개변수 구문을 사용하면 모든 변수를 전달받는다. 또한 함수의 정의에 마지막 매개변수는 하나만 존재한다.
예제를 통해 나머지 매개변수를 사용해보자
1) 전달 받은 모든 수를 더하는 함수
function add(...numbers) {
let result = 0
numbers.forEach((num) => (result += num))
console.log(result)
}
const add = [1,2,3] // 6
const add = [1,2,3,4,5,6,7,8,9,10] // 55
2) user 객체를 만들어 주는 생성자 함수 만들기
function User(name, age, ...skills) {
this.name = name,
this.age = age,
this.skills = skills,
}
const user1 = new User('jihyun', 30, 'html', 'css')
const user2 = new User('yun', 25, 'JS', 'React')
const user3 = new User('jennie', 26, 'English')
console.log(user1)
// User { name: 'jihyun', age: 30, skills: [ 'html', 'css' ] }
console.log(user2)
// User { name: 'yun', age: 25, skills: [ 'JS', 'React' ] }
console.log(user3)
// User { name: 'jennie', age: 26, skills: [ 'English' ] }
배열이나 문자열 등을 풀어서 요소 하나 하나로 전개시킬 수 있다. 문법의 객체는 '반복가능(iterable)'해야한다.
나머지 매개변수(...)와 형태는 동일하지만 사용법은 다르다.
const arr = [1, 2, 3, 4];
const str = "jihyun";
console.log(...arr) // [1, 2, 3, 4]
console.log(...str) // "j" "i" "h" "y" "u" "n"
배열의 각 요소를 인자로 넘길때 apply()대신 전개구문을 활용하면 더욱 간편해진다.
function plus(a, b, c) {
return a + b + c;
}
const arr = [2, 3, 4]
const res1 = plus.apply(null, arr); // apply() 사용
const res2 = plus(...arr) // 전개구문 사용
일반 객체는 전개구문 문법의 객체가 될 수 없다
const obj = { a: 1, b: 2 }
console.log(...obj) // error
하지만 객체 내부에서는 사용이 가능하다
const user1 = { name : "jihyun", age : 20 }
const user2 = { ...user }
console.log(user2) // { name: "jihyun", age: 20 }
여기서 user2는 user1의 프로퍼티를 복제한 객체이다. 따라서 user1과 user2는 엄연히 다른 객체이다.
console.log(user1 === user2) // false
객체를 복제해서 프로퍼티를 변경할 수도 있다
const user1 = { name : "jihyun", age : 20 }
const user2 = { ...user, name : "yun" }
console.log(user2) // { name: "yun", age: 20 }
전개구문 활용
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
// 둘 이상의 배열 합치기
const result1 = [...arr1, ...arr2] // [1, 2, 3, 4, 5, 6]
// 배열에 요소 추가하기
cosnt result2 = [0, ...arr1, ...arr2, 7, 8, 9] // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]