spread 어떤 걸 가져와서 확장한다.
배열과 같이 반복 가능한 객체를 전개 구문을 사용해서 확장한다.
함수로 호출할 경우엔 0개 이상의 인수로
배열 리터럴에서는 요소로 확장할 수 있다.
객체 리터럴에서는 0개 이상의 키-값 쌍으로 확장할 수 있다.
let nums = [1,2,6,3,8,0,6,10,15];
// ...nums을 쓰게되면 nums배열에 있는 각 값들이 하나씩 밸류로 넘어간다.
console.log(Math.max(...nums));
//문자열에서도 사용가능
let str = 'hello';
let arr = [];
arr.push(...str);
console.log(arr); //[ 'h', 'e', 'l', 'l', 'o' ]
//바로 쓸 수도 있음
console.log([..."hello"]);//[ 'h', 'e', 'l', 'l', 'o' ]
//배열을 합칠 때도 가능
const cats =['Blue', 'Scout', 'Rocket'];
const dogs =['Rusty', 'Wyatt'];
const catAndDog =[...cats, ...dogs]
console.log(catAndDog) //[ 'Blue', 'Scout', 'Rocket', 'Rusty', 'Wyatt' ]
//원본값에는 영향을 주지 않고 복사해온다.
console.log(cats) // [ 'Blue', 'Scout', 'Rocket' ]
console.log(dogs)// [ 'Rusty', 'Wyatt' ]
//객체
const feline = {legs:4, family:'Felidae'};
const canine = {isFurry:true, family:'Caninae'};
//키 값이 같다면 spread할 때 뒤에오는 데이터로 덮어 씌워짐
const newObj = {...feline, ...canine};
const newObj2 = { ...canine, ...feline};
console.log(newObj) //{ legs: 4, family: 'Caninae', isFurry: true }
console.log(newObj2) //{ isFurry: true, family: 'Felidae', legs: 4 }
//원본값에 영향을 안 미침
console.log(feline); // { legs: 4, family: 'Felidae' }
console.log(canine); // { isFurry: true, family: 'Caninae' }
////키 밸류값 매칭
//오브젝트에서 배열이나 문자열을 spread하면 인덱스값이 키값 // 값이 value값으로 매칭된다.
console.log({...[2,4,5,6]}); //{ '0': 2, '1': 4, '2': 5, '3': 6 }
console.log({...'hello'}); //{ '0': 'h', '1': 'e', '2': 'l', '3': 'l', '4': 'o' }
//보통 객체를 복사할 때 spread를 활용한다.
//객체를 복사하는 경우 객체를 변형하지 않고 복사하기 위해서