Learn.09 바닐라 JS로 크롬 앱 만들기

Monroe·2021년 11월 18일
0
post-thumbnail

이번 강의는 헷갈리는 부분도 있고, 설명이 길어져서 포스터의 길이가 다소 긴 편이다.. conditionals 을 완벽히 이해하는 그날까지 화이팅..

🪄 Conditionals

Nomadcoder 바닐라 JS로 크롬 앱 만들기
about conditionals
#2.13~ #2.15

conditional(조건문)은 true인지 false인지 알려주기 때문에 아주 중요하다. 무언가를 확인해야 할 때 거의 대부분 사용한다고 한다.

예를 들어, 사용자가 로그인 되어 있다면, 무언가를 보여준다던지 사용자가 무언가를 할 때 반응하는 것을 만들 때 사용된다.

이것의 키워드는 if 다.

앞서, function 호출하는 법과 argument(인자)와 string, bloolean, number와 같은 data type를 연습해보고 if, else와 같은 조건문을 추가해본다.

이번 강의에서는 음주가 가능한 나이인지 아닌지를 알려주는 계산기를 만들 예정이다.

🪡 prompt()

const age = prompt("How old are you?"); 👈 이 부분에서 javascript의 코드 실행을 멈춘다.

console.log(age);
---
👉 After refreshing and the console result in the browser
> cancel button
null 👈console.log(age)는 age가 null이기 때문에 띄운 것
-
> Ok button
     👈 Empty string
-
> 156 after OK button
156
_

위와 같이 const age = 18와 같은 숫자 대신에 prompt라는 function을 사용한다. prompt는 사용자에게 창을 띄워 준다.

prompt는 2개의 argument를 받는다.

prompt(message?: string, default?: string)
하나는 message, 또다른 하나는 defalt다.
message는 사용자에게 message를 보여주고 값을 넣으라고 알려주는 역할을 할 것이다.

새로고침해서 브라우저를 살펴보면, 브라우저는 계속해서 로딩을 하고 있다는 표시를 띄울 것이고, console 창에는 아무것도 띄우지 않고, 내가 아까 prompt에 적은 "How old are you?"라는 알람창이 뜰 것이다.

이 때 페이지는 우리가 입력창에 문자를 넣기 전까지는 javascript를 일시정시 시킨다. 즉, prompt는 자바스크립트의 코드의 실행을 멈춘다.

하지만 요즘 인터넷 사이트를 보면 알 수 있듯이, prompt를 잘 쓰지 않는다. message가 안 예쁘고, css의 스타일을 적용시킬 수가 없고... 심지어 어떤 브라우저는 prompt같은 팝업을 제한하기 때문이다. 니코 쌤은 이것이 아주~~ 오래된 방법이라고 한다.

이제 우리는 사용자가 무엇을 입력하더라도 그걸 number로 바꾸는 작업을 할 것이다.

const age = prompt("How old are you?");

console.log(age);
---
👉 After refreshing and the console result in the browser
> 12345 입력 후
12345 👈 는 number로 인식된게 아니다.

value의 type을 보려면 typeof라는 키워드를 사용해야한다.

const age = prompt("How old are you?");

console.log(typeof age);
---
👉 After refreshing and the console result in the browser
> 1231231
string

typeof는 내가 저 입력창에 무엇을 적어도 string으로 인식한다.

그럼 어떻게 string을 number로 바꿀 수 있을까?
예를 들면, "15" => 15로 바꾸는 일 말이다.

🪡 parseInt()

parseInt(s: string, radix?: number) : number
A string to convert into a number.
Converts a string to an interger.

parseInt()는 string을 number로 바꿔주는 역할을 한다.

const age = prompt("How old are you?");

parseInt("15")

console.log(typeof "15", typeof parseInt("15"));
---
👉 After refreshing and the console result in the browser
> 132124
string number 👈 number 부분이 parseInt("15")를 입력한 곳
const age = prompt("How old are you?");

console.log(age, parseInt(age));
---
👉 After refreshing and the console result in the browser
> 17
17 17 👈 왼쪽의 17이 string이고 오른쪽의 17이 parseInt()부분으로, number로 인식했다.

이제 그럼 이 17라는 숫자가 어떤 수보다 큰지 작은지 알 수 있다. string이면 숫자와 크기 비교를 할 수 없기 때문에, number로 변환하는 parseInt()를 사용하는 것이다.

const age = prompt("How old are you?");

console.log(age, parseInt(age));
---
👉 After refreshing and the console result in the browser
> asddsds
asddsds NaN 👈 NaN은 Not a Number

또, 위와 같이 사용자에게 나이를 물어봤는데 사용자가 숫자가 아닌걸 입력했을 경우도 인지 할 수 있다.

즉, parseInt()는 "lala"와 같은 string을 처리하지 않고 "1231"같은 숫자만 처리 가능하다.

const age = parseInt(prompt("How old are you?"));

console.log(age);
---
👉 After refreshing and the console result in the browser
> 18
18 👈 string이 아닌 number로 변환되서 나온다.
> lalala
NaN 👈 string은 number로 변환되지 않고 NaN로 나타난다.

실행 순서는 다음과 같다.

  1. 첫번째 function인, 사용자의 나이를 묻는 역할인 prompt가 "18"를 받고

  2. parseInt(prompt("How old are you?")) 👉 parseInt("18")와 같이 parseInt를 실행한다.

  3. 그러면 parseInt는 "18"를 18로 변환할 것이다.

🪡 isNaN()

isNaN(number: number): boolean
A numeric value.
Returns a Boolean value that indicates whether a value is the reserved value NaN(Not a Nunber).

이 function은 boolean(true or false)으로 판별해서 알려준다.

내가 isNaN를 사용할때, 하나의 argument(인자)를 주면
isNaN(number : number) < 인자의 위치
number인지 아닌지 알려준다.

const age = parseInt(prompt("How old are you?"));
console.log(isNaN(age));
---
👉 After refreshing and the console result in the browser
> 18
false 👈 isNaN(age)를 인식함
> lalala
true 👈 "

처음엔 엥? 이게 뭐지 알맞게 된건가 싶었다

isNaN은 boolean을 return한다. 여기의 isNaN(age)가
number가 아닌것(NaN)이 아니란 뜻이다. 즉, false 는 숫자로 인식했다는 뜻이다.

또, lalala라고 입력하고 보낸건 true라고 인식했는데 이 뜻은 숫자로 인식하지 않았다(NaN) 고 한 것이다.

🪡 if(condition){}else{}

이제 드디어 condition에 들어왔다..

if(condition){
	///condition===true 👈 조건이 참(true)이면 이 코드가 실행되고
} else{
	///condition===false 👈 조건이 거짓(false)이면 이 코드가 실행된다.
}

condition은 true 이거나 false 딱 두 가지 뿐이다.

if(condition){
	/// condition === true
}
/// if(conditioon) < 이 안에 condition이 true면 { }이 안이 실행되는데, false면 실행되지 않는다.

그러면 아까 전에 true와 false를 주었던 코드, isNaN()을 실행시켜보자

const age = parseInt(prompt("How old are you?"))

if(isNaN(age)){
	console.log("Please write a number.");
}
👉 After refreshing and the console result in the browser
> 18 을 입력하면
   👈 true이기 때문에 숫자가 나오지 않고
-
>lala
Please write a number 👈 false여서 내가 쓴 문구가 나오는 것이다
-

🪡 else if(){}

이제 else를 써서 true 였을 때 문구를 띄워보자

const age = parseInt(prompt("How old are you?"));
if(isNaN(age)){
	console.log("Please write a number.");
} else {
	console.log("Thank you for writing your age.");
}
👉 After refreshing and the console result in the browser
> 18
Thank you for writing your age. 👈 false
> dfdfdf
Please write a number 👈 true

조건을 두 개 이상 걸어야할 때는 다음과 같이 쓴다.

const age = parseInt(prompt("How old are you?"));
if(isNaN(age)){
	console.log("Please write a number.");
} else if(age < 18){
	console.log("You are too young.");
} else {
	console.log("You can drink");
}
👉 After refreshing and the console result in the browser
> afaf
Please write a number.
> 17
You are too young.
>20
You can drink

else if는 else와 비슷하지만 if를 더한 개념

즉, else if는 if(){}가 false일 때 한가지 condition을 더 사용할 수 있다는 것이다.

하나는 age가 NaN 일 때 Please write a number를 띄울 것이고
또 하나는 age가 number이면 다른 condition을 확인한다.

① if(isNaN(age)){}가 true면 console.log("Please write a number."이 실행될 것이고
② false면, javascript는 else if(age < 18) 이 condition을 확일 할 것이다.
③ else if(age < 18)가 true면, console.log("You are too young.");이 실행될 것이고
④ false면, console.log("You can drink");이 실행된다.

즉, console.log("You can drink");를 띄우려면 if(isNaN(age))와 else if(age<18) 둘 다 false를 띄워야한다.

🪡 AND operator, OR operator

AND operator는 && / OR operator는 ||로 표시한다.

AND

true && true === true
false && true === false
true && false === false
fasle && false === false

AND operator는 true가 되려면 둘다 true가 되고 나머지는 false가 된다.

OR

true || true === true
false || true === true
true || false === true
false || false === false

이와 같이 OR operator는 false가 되려면 둘 다 fasle여야 한다.

const age = parseInt(prompt("How old are you?"));

if(isNaN(age)){
	console.log("Please write a number.");
} else if(age < 18){
	console.log("You are too young.");
} else if(age >= 18 && age <= 50){
	console.log("You can drink");
} else if(age > 50 && age <= 80){
	console.log("You should exercise");
} else(age > 80) {
	console.log("You can do whatever you want.");
}
👉 After refreshing and the console result in the browser
> lala
Please write a number.
-
> 15
You are too young.
-
> 19
You are too young.
-
>51
You should exercise
-
>99
You can do whatever you want.

여기서 음의 정수나 소수점을 쓸 때 "You are too young"이란 문구가 뜬다. 이건 어떻게 해결해야할까?

const age = parseInt(prompt("How old are you?"));

if(isNaN(age) || age < 0 ){
	console.log("Please write a real positive number.");
} else if(age < 18){
	console.log("You are too young.");
} else if(age >= 18 && age <= 50){
	console.log("You can drink");
} else if(age > 50 && age <= 80){
	console.log("You should exercise");
} else if(age > 80) {
	console.log("You can do whatever you want.");
} else if(age === 100) {
	console.log("wow you are wise");
}
👉 After refreshing and the console result in the browser
> -50
please write a real positive number
-
> 0.3
please write a real positive number
-
> 100
You can do whatever you want. 👈 이 부분은 원래 100을 입력했을때 else if(age === 100)이 실행됐어야 했다.

if(isNaN(age) || age < 0 ){~}와 같이 OR 연산자를 쓰면 된다.

또, else if(age === 100)처럼 값이 동일한지 확인 할 수 있다. 만약에 적은 순서가 정확하지 않으면 이 condition은 실행되지 않는다.

else if(age === 100) {
	console.log("wow you are wise");
} else if(age > 80) {
	console.log("You can do whatever you want.");
}
👉 After refreshing and the console result in the browser
> 100
wow you are wise
> 120
You can do whatever you want

왜냐하면 첫번째 이유는 age가 80보다 클 경우 You can do whatever you want 가 실행되는 것이고, 두번째 이유는 javascript는 코드를 위에서 아래로 읽기 떄문이다.

그래서 if(age > 80)이 if(100 > 80)이기 때문에 실행하는 것이다. 그 외에도 105 > 80 도 마찬가지다.

그럼 어떻게 올바르게 실행 시켜야하나? 답은 위와 같이 if(age === 100)이 if(age > 80)보다 위에 있어야 실행된다.

참고로 if(age === 100) 말고 age가 100이 아니라면~ 을 묻는 방법은 if(age !== 100)을 쓰면 된다.

🧵 OR, AND 연습

1)

if((a && b) || (c && d)){}

true && true || true && true === true
true && false || true && false === false
false && ture || false && ture === false
false && false || false && false === false

true && false || true && true
① false || true
② true

true && true || false && false
① true || false
② true

false && false || true && false
① false || fasle
② fasle

6 > 2 && 10 > 15 || 8 < 6 && 9 > 10
① true && false || false && false
② false || false
③ false

2)

if((a && b) || (c && d) || (x || y)){}

true && false || true && true || false || true
① false || ture || ture
② true

false && ture || false && false || false || true
① false || false || true
② true

true && false || true && false || false || false
① false || false || false
② false

3)

if((a && b) || (c && d) && (x || y)){}

true && false || fasle && false && true || true
① false || false && true
② false && true
③ false

profile
monroe=pearl-mairs / JS 배우는 중

0개의 댓글