728x90
반응형
스프레드 문법은 for...of 문으로 순회가능한 이터러블에 한정된다
...[1,2,3] 을 하면 1 2 3이 나옴
이때 1 2 3은 값들의 목록이다
값이 아니라 개별적인 값들의 목록이기에
스프레드 문법의 결과는 변수에 할당이 불가능하다
const test=...[1,2,3] //SyntaxError
Rest 파라미터와 차이
Rest 파라미터는 함수에 전달된 인수들의 목록을 배열로 전달받기 위해
스프레드는 펼치기 위해
function foo(...rest){
console.log(rest); //[1,2,3]
}
foo(...[1,2,3])
배열 리터럴 내부에서 사용하는 경우
const arr=[...[1,2],...[3,4]]
console.log(arr); //[1,2,3,4]
const arr1=[1,4]
const arr2=[2,3]
arr1.splice(1,0,...arr2)
console.log(arr1); //[1,2,3,4]
//slice 얕은 복사
const origin=[1,2]
const copy=[...origin]
console.log(copy); //[1,2]
이터러블을 배열로 변환
function sum(){
return [...arguments].reduce((pre,cur)=>pre+cur,0)
}
console.log(sum(1,2,3));
const sum=(...args)=>args.reduce((pre,cur)) => pre+cur,0)
객체 리터럴 내부에서 사용
// 뒤에 위치한 프로퍼티로 병합됨
const merged={...{x:1,y:2},...{y:10,x:3}}
console.log(merged);
// 뒤에 위치한 프로퍼티로 바뀜
const change={...{x:1,y:2},y:10}
console.log(change);
// 추가
const added={...{x:1,y:2},z:0}
console.log(added);
{ x: 3, y: 10 }
{ x: 1, y: 10 }
{ x: 1, y: 2, z: 0 }
디스트럭처링 할당
디스트럭처링시 우변에 이터러블을 할당해야 한다. 아니면 오류 발생
const [x,y]=[1,2]
const [a,b]={} //TypeError: {} is not iterable
개수가 일치하지 않아도 순서대로 할당됨
const [a,b]=[1]
// 1 undefined
const [e,f]=[1,2,3]
console.log(e,f) // 1,2
const [a,b,c=3]=[1,2]
1,2,3
URL 파싱해서 객체를 생성해 반환하는 예제
function parseURL(url=''){
/*
'://' 앞의 문자열
'/' 이전의 '/'로 '/'로 시작하지 않는 문자열
'/' 이후의 문자열을 검색한다
*/
const parsedURL=url.match(/^(\w+):\/\/([^/]+)\/(.*)$/)
console.log(parsedURL);
[
'https://www.naver.com/extraurl',
'https',
'www.naver.com',
'extraurl',
index: 0,
input: 'https://www.naver.com/extraurl',
groups: undefined
]
if(!parseURL) return{}
const [a,b,c]=parsedURL
return {a,b,c}
}
const parsedURL=parseURL('https://www.naver.com/extraurl')
console.log(parsedURL);
Rest 요소 사용
const [x,...y]=[1,2,3]
console.log(x,y) // 1 [2,3]
객체 디스트럭처링 할당
const user={firstName:'Ungmo',lastName:'Lee'}
// 프로퍼티 키를 기준으로 할당이 되기 때문에 순서는 의미가 없다
const {lastName,firstName}=user
// const {lastName:lastName,firstName:firstName} 과 같다. 축약표현을 사용
// const {lastName:ln,firstName:fn} 이런식으로 이름을 정해서 사용할 수 있음
console.log(firstName,lastName); //Ungmo Lee
//기본값 설정가능
const {defaultfName='Steve',dLastNme}={dLastN:'Ko'}
// 디스트럭처링 할당을 위해 할당받을 변수를 선언해줘야한다
const {lNmae,fName}={firstName:'Ungmo',lastName:'Lee'}
유용한 사용법
const str='Hello'
const{length}=str
console.log(length); //5
const todo={id:1,name:'dd',con:'dqw'}
const {id}=todo
console.log(id); //1
function printTodo({name,con}){
console.log(`이름은 ${name}이고 con은 ${con}입니다`)
}
printTodo(todo)
const todos=[
{ido:1,name:'jan',con:'hi'},
{ido:2,name:'feb',con:'fi'},
{ido:3,name:'mar',con:'mi'}
]
const [,{ido}]=todos // ido는 2부터 나옴
const muti={
a:{
b:{
c:'there'
}
}
}
const {a:{b:{c}}}=muti
console.log(c); //there
728x90
반응형
'JavaScript' 카테고리의 다른 글
브라우저의 렌더링 과정 (0) | 2022.07.07 |
---|---|
Set과 Map (0) | 2022.06.30 |
이터러블 (0) | 2022.06.29 |
RegExp (0) | 2022.06.29 |
배열 (0) | 2022.06.28 |