function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers); //6 출력
let parts = ['two', 'three'];
let numbers = ['one', ...parts, 'and', 'four'];
console.log(numbers); //['one', 'two', 'three', 'and', 'four'] 출력
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
console.log(arr1); //[0, 1, 2, 3, 4, 5] 출력
let arr = [1, 2, 3];
let arr1 = [...arr]; // arr.slice() 와 유사
arr1.push(4);
console.log(arr1); // [1, 2, 3, 4]
console.log(arr); // arr 은 그대로 [1, 2, 3]을 유지
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };
console.log(clonedObj); //{foo: 'bar', x: 42}
console.log(mergedObj); //{foo: 'baz', x: 42, y: 13}
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(...theArgs) {
return theArgs.reduce((previous, current) => {
retrun previous + current;
});
}
sum(1, 2, 3) //6 출력
sum(1, 2, 3, 4) //10 출력
let arr = ['Thomas', 'Holland']
let [firstName, lastName] = arr;
console.log(firstName); //Thomas
console.log(lastName); //Holland
console.log(arr); //['Thomas', 'Holland']
let [firstName, ,lastName] = ["Thomas", "Stanley", "Holland", "Spider-man"];
console.log(lastName); //Holland
let [name = "Guest", surname = "Anonymous"] = ["Amy"];
console.log(name); //Amy
console.log(surname); //Anonymous
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
//아래 코드와 위의 코드는 동일한 결과임
//let {width, title, height} = options;
console.log(options);
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title: t, width: w, height: h} = options;
console.log(t); //Menu
console.log(w); //100
console.log(h); //200
console.log(options); //{title: 'Menu', width: 100, height: 200}
let options = {
title: "Menu"
};
let {width = 100, height = 200, title} = options;
console.log(title); // Menu
console.log(width); // 100
console.log(height); // 200
cf) 선언 없이 객체 리터럴(object literal) 비구조화 할당
var a, b;
({a, b} = {a: 1, b: 2});
console.log(a); // 1
console.log(b); //2