조건문 Nesting

stayby94·2023년 8월 5일

JS문법

목록 보기
10/15

만약 유저가 입력한 비밀번호에 공백이 있는지와 문자열의 길이를 같이 확인하고 싶다면??

  • 각각 따로 조건문을 만들면 결과가 2번 나오게 되는데 사용자 입장에서 상당히 번거로움.
  • 보통은 사용자에게 한번에 하나의 피드백만 제공함.
  • 아래와 같은 경우인데..
if(password.length >= 6){
	console.log("goooood")
} else {
	console.log("password too short")
}

if(password.indexOf(' ')===-1){
	console.log("goooood")
}else{
	console.log("password cannot contain spaces!")
}

비밀번호가 6자리 이상이면 바로 결과를 내지말고 공백이 있는지도 확인하도록 조건문을 중첩해서 쓸 수 있음.

if(password.length >= 6){
	if(password.indexOf(' ')===-1){
	console.log("goooood")
	}else{
	console.log("password cannot contain spaces!")
	}
} else {
	console.log("password too short")
}

중첩하면 약간 코드가 무거워질 수 있음.

0개의 댓글