
1. 조건문
- 특정 조건이 참인지 거짓인지에 따라 코드의 실행 흐름을 제어하는 구문
prompt
함수를 사용해 값을 받아 출력하기prompt
: 사용자가 입력을 제공할 수 있는 대화 상자를 생성하는 함수- css 적용이 안됨
const age = prompt("How old are you?"); console.log(age);







- 받은 타입을 변경하여 출력하기
const age = prompt("How old are you?"); console.log(typeof age); // 입력받은 값의 타입 확인하기
- default 값이 String이기에 변형이 필요함
- 숫자로 인식되어야 수 비교 등 처리를 할 수 있음


const age = prompt("How old are you?"); console.log(typeof age); // 입력받은 값의 타입 확인하기 console.log(typeof age, typeof parseInt(age)); // 정수로 타입 변경하기


const age = prompt("How old are you?"); console.log(typeof age); // 입력받은 값의 타입 확인하기 console.log(age, parseInt(age)); // 정수로 타입 변경하기


- 숫자로 입력했는지 확인 가능
- NaN : Not a Number


- 숫자를 입력하지 않은 경우 메세지 띄우기
const age = parseInt(prompt("How old are you?")); console.log(age);

const age = parseInt(prompt("How old are you?")); console.log(isNaN(age));
const age = parseInt(prompt("How old are you?")); console.log(isNaN(age));





- 조건문의 형태
if(condition) { // 참일 때 } else { // 그외 = 거짓일 때 }
const age = parseInt(prompt("How old are you?")); if(isNaN(age)) { // 입력받은 값이 숫자가 아닐 console.log("숫자를 입력해주세요~"); }


- if/else 구문
const age = parseInt(prompt("How old are you?")); if(isNaN(age)) { // 참인 경우 console.log("숫자를 입력해주세요~"); } else { // 거짓인 경우 console.log("당신의 나이를 입력해주셔서 감사합니다~!"); }


- if/else if/else구문
const age = parseInt(prompt("How old are you?")); if(isNaN(age)) { // 입력받은 값이 숫자가 아닐 console.log("숫자를 입력해주세요~"); } else if(age < 18){ // 18세보다 어릴 때 console.log("18세 보다 어리시네요ㅜ") } else { // 18세 이상일 때 console.log("원하는 음료를 마실 수 있으세요~!"); }




const age = parseInt(prompt("How old are you?")); if (isNaN(age)) { // 입력받은 값이 숫자가 아닐 때 console.log("숫자를 입력해주세요~"); } else if (age < 18) { // 18세보다 어릴 때 console.log("18세 보다 어리시네요ㅜ"); } else if (age >= 18 && age <= 50) { // 18세 이상이고 50세 이하일 때 console.log("원하는 음료를 마실 수 있으세요~!"); } else { // 50세 초과일 때 console.log("원하는 음료를 마실 수 없으세요"); }






Share article