{
var foo = 10;
}
if(조건식){
// 조건식이 참이면 이 코드 블록 실행
}else{
// 조건식이 거짓이면 이 코드 블록 실행
}
var num = 2;
var kind;
if(num>0) kind = '양수';
else if(num) kind = '음수';
else kind = '영';
console.log(kind); // 양수
// 삼항 조건 연산자로 바꿔 쓸 수 있다.
var kind = num ? (num > 0 ? "양수" : "음수") : "영"
switch(표현식){
case 표현식1:
switch 문의 표현식과 표현식1이 일치하면 실행될 문;
break;
case 표현식2:
switch 문의 표현식과 표현식2이 일치하면 실행될 문;
break;
default:
switch 문의 표현식과 일치하는 case 문이 없을 때 실행될 문;
}
-switch 문은 다양한 상황에 따라 실행할 코드 블록을 결정할 때 사용한다.
var month = 11;
var monthName;
switch(month){
case 1: monthName = 'January';
case 2: monthName = 'February';
case 3: monthName = 'March';
case 4: monthName = 'April';
case 5: monthName = 'May';
case 6: monthName = 'June';
case 7: monthName = 'July';
case 8: monthName = 'August';
case 9: monthName = 'September';
case 10: monthName = 'October';
case 11: monthName = 'November';
case 12: monthName = 'Desember';
default: monthName = 'Invalid month';
}
console.log(monthName); // Invalid month
var month = 11;
var monthName;
switch(month){
case 1: monthName = 'January';
break;
case 2: monthName = 'February';
break;
case 3: monthName = 'March';
break;
case 4: monthName = 'April';
break;
case 5: monthName = 'May';
break;
case 6: monthName = 'June';
break;
case 7: monthName = 'July';
break;
case 8: monthName = 'August';
break;
case 9: monthName = 'September';
break;
case 10: monthName = 'October';
break;
case 11: monthName = 'November';
break;
case 12: monthName = 'Desember';
break;
default: monthName = 'Invalid month';
}
console.log(monthName); // November
for(변수 선언문 또는 할당문; 조건식; 증감식){
조건식이 참인 경우 반복 실행될 문
}
for(var i = 0; i < 2; i++){
console.log(i)
}
// 0
// 1
// 무한 루프
for(;;){...}
for(var i = 0; i <= 6; i++){
for(var j= 1; j <=6; j++){
if(i + j ===6) console.log(`[${i}, ${j}]`);
}
}
// [1, 5]
// [2, 4]
// [3, 3]
// [4, 2]
// [5, 1]
var count = 0;
while(count < 3){
console.log(count); // 0 1 2
count++;
}
var count = 0;
while(true){
console.log(count); // 0 1 2
count++;
if(count ===3) break;
} // 0 1 2
var count = 0;
do{
console.log(count) // 0 1 2
count++;
}while (coutn < 3);
// foo 라는 식별자가 붙은 레이블 블럭문
foo: {
console.log(1);
break foo;
console.log(2);
}
console.log('Done!')
var string = 'Hello world.'
var search = 'l'
var coutn = 0;
// 문자열은 유사 배열이므로 for 문으로 순회할 수 있다.
for(var i = 0; i < string.length; i++){
//'l'이 아니면 현 지점에서 실행을 중단하고 반복문의 증감식으로 이동
if(string[i] !== search) continue;
count++; // continue 문이 실행되면 이 문은 실행되지 않는다
}
console.log(count) //3