Javascript 기초문법-2.2 조건문, 반복문

tiinto·2022년 5월 19일
0

Sparta

목록 보기
4/11

앱개발 종합반 1주차

5) 조건문

[ if, else if, else 조건문 ]

#예시 1
조건1, 조건 2, 그외

function is_adult(age){
	if(age > 19){
		console.log("성인")
	}else if(age > 10) {
		console.log("청소년")
	}else{
        console.log("어린이")
    }
}

is_adult(30)
▶ 성인

조건문에는 if, else if, else 함수를 쓴다.

#예시2
조건 여러개 추가

function is_adult(age){
	if(age > 19){
		console.log("성인")
	}else if(age > 16) {
		console.log("고등학생")
	}else if(age > 13) {
		console.log("중학생")
	}else if(age > 7) {
		console.log("초등학생")
    }else{
        console.log("어린이")
    }
}

is_adult(15)
▶ 중학생

else if로 조건을 여러개 추가할 수 있다.

조건문은 순서가 중요한 듯. 단계별로 조건을 할당해야 한다.

그렇지 않으면 부적절한 값이 도출된다.

function is_adult(age){
	if(age > 20){
		console.log("성인")
	}else if(age > 7) {
		console.log("초등학생")
    }else if(age > 13) {
		console.log("중학생")
	}else if(age > 16) {
		console.log("고등학생")
	}else{
        console.log("어린이")
    }
}
is_adult(15)
▶ 초등학생

[AND 조건 & OR 조건]

  • 부등호는 >,<,=로 표시
  • 동일 조건은 ==
function is_adult(age, sex){
if(age > 19 && sex == '여'){
alert('성인 여성')
} else if (age > 19 && sex == '남') {
alert('성인 남성')
} else {
alert('청소년')
}
}

AND 조건은 && 을 쓴다.

function is_adult(age, sex){
if (age > 65 || age < 10) {
alert('탑승 불가')
} else if(age > 19 && sex == '여'){
alert('성인 여성')
} else if (age > 19 && sex == '남') {
alert('성인 남성')
} else {
alert('청소년')
}
}

is_adult(25,'남')

OR 조건은 || 을 쓴다.


6) 반복문

[일반 반복문]

for (let i = 0; i < 10; i++) {
	console.log(i);
}
▶ 0
▶ 1
▶ 2
▶ 3
▶ 4
▶ 5
▶ 6
▶ 7
▶ 8
▶ 9

반복문은 for 함수를 쓴다.
범위를 지정할 때는 ; (세미콜론) 을 꼭 써줘야 함

for (let i=0; i<10; i++)
- i=0; : i는 0 번째부터 
- i<10; : 10번째 미만(9번째)까지
- i++ : 1씩 증가시킨다.

[리스트에서의 반복문]

아래 코딩한 걸 보면...
people.length 는 6이니까
0부터 6 미만까지 1씩 증가하면서 도는 반복문인 것
(i는 리스트에서 순서가 되는 것이죠)
i가 1씩 증가하면서, people의 원소를 차례대로 불러오게 됨

let people = ['철수','영희','민수','형준','기남','동희']


for (let i = 0 ; i < people.length ; i++) {
	console.log(people[i])
}
▶ 철수
▶ 영희
▶ 민수
▶ 형준
▶ 기남
▶ 동희

[리스트&딕셔너리 복합구조에서의 반복 조건문]

다음의 복합구조 자료에서
70점 미만 조건에 해당하는 학생들을 찾으려면

let scores = [
{'name':'철수', 'score':90},
{'name':'영희', 'score':85},
{'name':'민수', 'score':70},
{'name':'형준', 'score':50},
{'name':'기남', 'score':68},
{'name':'동희', 'score':30},
]

for (let i = 0 ; i < scores.length ; i++) {
    if(scores[i]['score'] < 70){
        console.log(scores[i])
    }
}

이 때 console.log를 통해 보여주는 대상은
if 조건문에 해당하는 값을 표시하고자 하므로
if 함수, 즉, if(){} 안에 적어야 한다.

만약 if 함수 밖에 쓰면 조건에 따른 값은 표시되지 않는다.

for (let i = 0 ; i < scores.length ; i++) {
    if(scores[i]['score'] < 70){
    }
        console.log(scores[i])
}
▶ {name: '철수', score: 90}
▶ {name: '영희', score: 85}
▶ {name: '민수', score: 70}
▶ {name: '형준', score: 50}
▶ {name: '기남', score: 68}
▶ {name: '동희', score: 30}

0개의 댓글