[포스코X코딩온] 웹개발자 입문과정 8.1

HM·2023년 4월 27일
0

POSCO CODINGON KDT

목록 보기
14/18
post-thumbnail

...rest

  • 관례상 rest(단어)를 쓴다 나머지니까

객체에서의 ...rest

  • 구조분해 할당을 통해서 사용할 수 있다.

const me = {
	from : "korea",
	language:"korean",
    hobby:"movie",
  	phone:"010-1234-5678",
    }

const { from,language,hobby,phone } = me; // 구조분해 할당

console.log(phone)//"010-1234-5678"

이 때 const {from, ...rest} = me; 를 하게 되면,

console.log(rest)//  {language ...,hobby...,phone...,} 

from을 제외한 나머지값들이 rest에 저장돼 출력 된다.

...rest를 이용해서
me 객체에서 원하는 정보를 제외하고 보낼 수 있다.

  • me 객체에서 개인정보인 phone 을 빼고 보여주고 싶을때
const {phone,...withoutphone} //rest 써두됨....
console.log(withoutphone)

프론트단에서 정보를 보여줄 때, 다른사이트로 넘길 때 필요하지 않은 정보는 제외하고 넘길 수 있다.

배열에서의 ...rest

  • 위랑 비슷하다
const myfriends=["leo","cola","game"] // :sad:

// const friend1 = myfriend[0]
// const friend2 = myfriend[1]
// const friend3 = myfriend[2]

const [friend1,friend2,friend3] = myfriends

// or 


const [friend1,...rest] = myfriends

...rest 를 파라미터로 쓸 때 (함수)

  • spread문법과 동일하게 매개변수 앞에 ...같이 쓴다.

function number = (one,two,three) {
  console.log(one,two,three) //1,2,3
}
  
  number(1,2,3)

function number = (one,...rest) {
  console.log(one)//1
  console.log(rest)//[2,3]
}
// 이 때, rest 는 배열의 형태로 나타낸다
  • 파라미터의 개수를 안 정해도 된다 (타입스크립트 : ?)
function number = (one,...rest) {
  console.log(rest)//[2,3,4,5,6,7,8,9]
}
number(1,2,3,4,5,6,7,8,9)
  • 위와 비슷한 특성 때문에 특정 값만 따로 추출할 수 있다.
function me = (phone,...rest) {
  console.log(rest) // korean,korea,...
}
me(01012345678,korean,korea, ...,)
  

...rest 를 이용한 응용방법

  • react상에서 자주 사용할 것같은 응용법
//app.jsx
<PasswordInput
type='password'
value={value}
onChange={onChange}
isValid={isValid}
>
//PasswordInput.jsx
  
export default const PasswordInput = ({isValid,...rest}) =>{
   //isValid 만 가져와서, 유효성 검사를 한다.
   if (!isValid) return;
   
   return 
  <input {rest}> // rest를 이용해서 input 태그의 속성을 그대로 넣을 수 있다.
   
 }
  • 익숙해진다면 가독성 좋고 간결한 코드 작성이 될 수 있을듯 하다.
profile
It's the smurf smurf smurf!

0개의 댓글