[JS] #16 JavaScript 의사결정

jaeyeon_lee·2024년 1월 29일

유데미

목록 보기
13/22

⛅ JavaScript 의사결정

Boolean Logic

비교 연산자

> //크다
< //작다
>= //크거나같다
<= //작거나같다
== //같다
!= //같지않다
=== //같다
!== //같지않다

이중등호 vs 삼중등호

  • 이중등호 : 두 값이 같은지 알 수 있음. type구별 X (두 값이 다른 타입이면 같아지도록 강제로 변환함)
  • 삼중등호 : 타입까지 구별해서 두 값이 같은지 비교.

Console.log() : 인수를 콘솔창에 출력함

Alert() : 사용자에게 뭔가를 출력해줌 (콘솔에서 출력 X)

Prompt() : 사용자에게 인수를 받아들임.

JS실행 방법

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JaeYeon</title>
</head>
<body>
    <h1>Hi</h1>
    <script src="app.js"></script>
</body>
</html>
console.log("hi my JS code~!!!")

js 파일을 HTML script부분에 추가해줌!

Conditionals (조건문)

IF statement

let rating=3;
if (rating ===3) {
	console.log("You are a SuperStar!");
}
if ( 조건 ) {
	조건이 참이면 실행될 것들
}else {
	조건이 참이 아니면 실행될 것들
}

Else IF

let rating=2;
if (rating ===3) {
	console.log("You are a SuperStar!");
}
else if (rating ===2){
	console.log("Meets expectations");
}

if ( 조건1 ) {
	조건1이 참이면 실행될 것들
}else if ( 조건2 ) {
	조건2가 참이면 실행
}else {
	조건1,2가 참이 아니면 실행
}

🖥️  첫 번째 조건문 연습

조건문을 사용하는 연습을 해 보겠습니다. 코드를 반복 실행하고 테스트할 수 있도록 미리 정의된 함수(아직 강의에서 다루지 않은 내용) 안에 코드를 작성하시기 바랍니다.

  • index.js 내에 있는 두 개의 주석 사이에 코드를 작성하세요.
  • num이라는 변수에 자동으로 액세스할 수 있을 것입니다. 어떤 식으로든 'num' 변수의 값을 변경하거나 재정의하지 마세요. 여러분의 코드를 테스트할 때 num값을 설정하여 다양한 결과를 테스트할 수 있도록 하겠습니다.
  • num값이 짝수이면 "even"을 출력하세요. num 값이 홀수이면 아무 작업도 수행하지 마세요.
function isEven(num){
   if (num % 2 === 0){
	   console.log("even")
   }
}

🖥️ getColor 조건문 연습

조건문을 사용하는 연습을 해 보겠습니다. 코드를 반복 실행하고 테스트할 수 있도록, 미리 정의된 함수(아직 강의에서 다루지 않은 내용) 안에 코드를 작성하시기 바랍니다.

  • index.js 내에 있는 두 개의 주석 사이에 코드를 작성하세요.
  • phrase라는 변수에 자동으로 액세스할 수 있을 것입니다. 어떤 식으로든 'phrase' 변수의 값을 변경하거나 재정의하지 마세요. 여러분의 코드를 테스트할 때 phrase값을 설정하도록 하겠습니다.
  • 여러분이 할 일은 다음 규칙에 따라 색상을 출력하는 것입니다:
    `1. if phrase is 'stop', you should print out 'red'
  1. if phrase is 'slow', you should print out 'yellow'
  2. if phrase is 'go', you should print out 'green'
  3. if phrase is anything else, you should print out 'purple'`
function getColor(phrase){
    if (phrase === "stop"){
        console.log("red")
    }else if(phrase === "slow"){
        console.log("yellow")
    }else if(phrase === "go"){
        console.log("green")
    }else{
        console.log("purple")
    }
}

조건문 Nesting

const password = prompt("pleas enter a new password");

if(password.length >=6){ //비밀번호 길이가 6이상일때 실행
	console.log("Long enough password!")
	if(password.indexOf(' ') ===-1){ // 비밀번호 공백이 없는지 확인
		console.log("Good Job! No space!")
	}else{
		console.log("Password cannot contain spaces!")
	}
}else{
	console.log("password too short! must be 6+ characters!")
}

🖥️ 중첩된 조건문 실습

이제 조금 색다른 것을 해볼 시간입니다. num이라는 변수를 사용하는 중첩된 조건문을 제공해 드렸습니다. num변수의 값을 다른 숫자로 변경하여 "YOU GOT ME!"가 출력되도록 해 보세요. num값 외에는 아무것도 변경하지 마세요! 조건문은 그냥 놔두세요!

const num = 102; 

if(num <= 100) {
    if(num >= 50) {
        console.log("HEY!");
    }
} else {
    if (num < 103) {
        if(num % 2 === 0){
            console.log("YOU GOT ME!");
        }
    }
}

Truthy & Falsy Values

const userInput = prompt("Enter something");

if (userInput){
	console.log("TRUTHY!")
}else {
	console.log("FALSY!")
}

조건에 userInput만 넣으면 불리언으로 변환되어 아무런 텍스트를 적어도 truthy가 나옴! 빈 문자열은 falsy가 나옴

⇒ 변수나 입력등 다른 곳에서 가져온 것이 있는 상황에서 실제로 존재하는지 문자열 내부 값이 있는지 등을 확인할 수 있음

Logical Operators

AND ( && )

1 <= 4 && 'a' === 'a' ; //true
9 > 10 && 9 >= 9 ; //false
'abc'.length === 3 && 1+1 === 4; //false

조건 모두가 참이여야지 문장 전체가 참!

const password = prompt("pleas enter a new password");

if(password.length >=6 && password.indexOf(' ') ===-1){
	console.log("Good Password!")
}else{
	console.log("Not Good Password")
}

🖥️ Logical AND Mystery 연습

mystery라는 변수를 사용하는 조건문을 제공해 드렸습니다. 조건문이 true가 되고 콘솔에 "YOU GOT IT"이 출력되도록 mystery값을 변경해 주세요. 1번 라인에 있는 mystery값 외에는 아무것도 변경하지 마세요!

const mystery = 'Purple7'; 

if(mystery[0] === 'P' && mystery.length > 5 && mystery.indexOf('7') !== -1){
    console.log("YOU GOT IT!!!");
}

OR ( || )

1 !== 1 || 10 === 10 //true
10/2 === 5 || null //true
0 || undefined //false

OR은 둘 중 하나가 참인지 따짐! 하나라도 참이면 문장 전체가 참!

const age = 25
if (age >= 0 && age < 5 || age >=65){ //0~5살이거나 65살이상
	console.log("FREE")
}else if (age >=5 && age <10){
	console.log("$10")
}else if (age >=10 && age <65){
	console.log("$20")
}else{
	console.log("Invalid age")
}

NOT ( ! )

값을 반전시키는 역할을 함. 거짓인 표현식 앞에 넣으면 참이 나옴!

let firstName = prompt("enter your first name");
if(!firstName){
	firstName = prompt("Try again!!!")
}

SWITCH

const day =2;
if (day ===1){
	console.log("Monday")
}else if(day ===2){
	console.log("Tuesday")
}else if(day ===3){
	console.log("Wednesday")
}else if(day ===4){
	console.log("Thursday")
}else if(day ===5){
	console.log("Friday")
}else {
	console.log("I dont know that")
}
const day =4;
switch (day) {
	case 1:
		console.log("Monday");
		break;
	case 2:
		console.log("Tuesday");
		break;
	case 3:
		console.log("Wednesday");
		break;
	case 4:
		console.log("Thursday");
		break;
	case 5:
		console.log("Friday");
		break;
	default:
		console.log("I don know that")
}

break 를 만날 때까지 계속 실행됨! 각각에 break를 넣어줘야 원하는 값만 나옴

profile
🙋🏻‍♀️

0개의 댓글