✅ 주석
//한줄짜리 주석
/* */ 여러줄 주석
/** */ JsDoc을 사용하면 좋음
--> 주석은 코드 자체를 설명하는 것이 아닌 왜(why)와 어떻게(how)를 설명하는 것이 좋음
/**
* JsDoc
* 주어진 두 인자를 더한 값을 반환함
* @param {*} num1 숫자1
* @param {*} num2 숫자2
* @returns num1 num2을 더한값
*/
function add(num1,num2){
return a+b;
}
✅ 예외처리
try{
예외가 발생할 것으로 예샹하는 문장;
...
}catch(error객체){
예외가 발생했을 대 처리할 문장;
...
}finally{
예외외 관계없이 무조건 실행할 문장;
...
}
function readFile(path){
throw new Error('파일 경로를 찾을 수 없음'); // 전달된 문자열(매개변수)이 담긴 에러객체가 생성!
return '파일의 내용을 리턴함' //실행안됨
}
function processFile(path){
let content;
try{
content = readFile(path);
}catch(error){ //자바랑 비슷. 그냥 변수만 넣으면 그 변수안에 에러객체 들어감
console.log(error);
content = '기본내용';
}finally{
console.log('에러의 발생 여부와 관계없이 실행할 문장을 작성함')
}
const result = '결과: '+ content;
return result;
}
const result = processFile('경로');
console.log(result);
--결과--
Error: 파일 경로를 찾을 수 없음
at readFile (/Users/jaewon/Desktop/study/javascript/day7/2_error1.js:2:11)
at processFile (/Users/jaewon/Desktop/study/javascript/day7/2_error1.js:9:19)
at Object.<anonymous> (/Users/jaewon/Desktop/study/javascript/day7/2_error1.js:20:16)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
에러의 발생 여부와 관계없이 실행할 문장을 작성함
결과: 기본내용
function func1(){
console.log('func1 호출되었어요!');
throw new Error('에러발생'); //throw를 던짐
}
function func2(){
try{
func1();
}catch(error){
console.log('예외처리 완료!!')
throw error;
}
}
function func3(){
try{
func2();
}catch(error){
console.log('여기에서 예외처리 또 완료!!'); //함수끼리 예외던지는 핸들링
}
}
func3();
console.log('프로그램이 정상적으로 종료되었습니다')
--결과--
func1 호출되었어요!
예외처리 완료!!
여기에서 예외처리 또 완료!!
프로그램이 정상적으로 종료되었습니다
✅ 모듈 (🌟🌟🌟🌟)
export default : 모듈에서 단1개만 사용할 수 있는 함수 또는 변수
export: 모듈에서 여러개를 사용할 수 있는 함수 또는 변수
모듈로 작성된 파일을 추가하는 방법
<script type="module" src="경로"></script>
-->type을 모듈이라 써야 인덱스에서 가져다 쓸 수 있다!
html파일
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>모듈</title>
<script type="module" src="./count.js"></script>// 반드시 타입을 module로 지정해야함
<script type="module" src="./main.js"></script>
<!-- 자바스크립트끼리 호환된다, 그래서 모듈이라는 개념이 생김 -->
</head>
<body>
<h2>모듈</h2>
</body>
</html>
js파일1(함수생성모듈)
let count = 0;
export default function increase(){
count++;
console.log(count);
}
export function getCount(){
return count;
}
//default는 함수명 안적어도 됨!
//여러개 쓸꺼면 default 쓰지말고,export써라
//하나일때는 default
// export default function getCount(){
// console.log(count);
// }
// SyntaxError: Duplicate export of 'default'
// 에러남, default여러개 만들지 못함
js파일2(함수사용모듈)
//default 있을 경우(default export만 있는경우)
// import increase from './count.js';
// increase();
//default없을 경우(named export만 있는경우)
// import {increase} from "./count.js";
// increase();
//named export가 여러개 있을경우
// import {increase, getCount} from "./count.js";
// increase();
// increase();
// increase();
// increase();
// console.log(getCount())
//defalut도 있고 named export도 있을경우
import {default as increase, getCount} from "./count.js";
increase();
increase();
increase();
increase();
console.log(getCount())
//별명을 줄 수도
// import {increase as add} from "./count.js";
// add();
//한꺼번에 불러오기 //default export가 있는경우 정확히 defalut export만 불러옴
// import * as cnt from './count.js';
// cnt.increase();
// cnt.increase();
// console.log(cnt.getCount());
--결과--
✅callstack
function func1(){
for(let i=0; i<100000; i++); // i<10000000000; 동기식으로 돈다, 차례대로, 그래서 시간 오래 걸린다
return 1;
}
function func2(){
return func1() +1;
}
function func3(){
return func2() +1;
}
console.log('프로그램을 시작합니다'); //여기서 시작
const result = func3();
console.log(result);
--결과--
프로그램을 시작합니다
3
func1이 다끝나야 다음꺼 실행
자바스크립트는 기본이 동기식!( 하나끝나면 끝날때까지 기다렸다가 다음꺼 실행 )
✅콜백함수는 비동기
function execute(){
console.log('1');
setTimeout(() => {
console.log('2');
},2000);
console.log('3');
}
execute();
//1->2->3
//1->3->2
//2->1->3
//2->3->1
//..? 뭘로 나올까
//1->3->2 이렇게 나온다
//콜백함수 쓰면 비동기식으로 나온다
--결과--
1
3
2
문제
아래 조건을 가진 프로그램을 작성해보자
1. 주어진 초가 지나면 콜백함수를 호출함
2.콜백함수의 내용은 '타이머 완료'라는 문자열을 출력
단,초는 밀리세컨드가 아닌 초로 입력 , 초는 0보다 작으면 에러를 발생, 콜백함수를 등록하지 않으면 에러가 발생
function runInDelay(callback, seconds){
if(!callback){
throw new Error('callback 함수를 전달해야합니다');
}
if(!seconds || seconds < 0){
throw new Error('seconds 는 0보다 커야합니다');
}
setTimeout(callback, seconds * 1000);
}
try{
runInDelay(() => {
console.log('타이머 완료')
},2);
}catch(error){
console.log(error);
}
--결과--
//1초후
타이머 완료
과제1-가위바위보
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="quiz1.js"></script>
</head>
<body>
<p id="user"> </p>
<p id="com" > </p>
</body>
</html>
// 바위 1 가위 2 보 3
//바위:1 - 이:3 비:1 진:2
//가위:2 - 이:1 비:2 진:3
//보:3 - 이:2 비:3 진:1
let result = clickBtn();
function clickBtn(){
const com = Math.floor((Math.random()*3)+1);
let result;
let user = prompt('가위,바위,보 중 하나를 입력하세요')
switch(user){
case "가위":
user=2;
break;
case "바위":
user=1;
break;
case "보":
user=3;
break;
}
console.log(com);
console.log(`user=${user}`)
console.log(`com=${com}`)
if(user ==1){
if(com==3){
result='lose';
}else if(com==2){
result='win';
}else{
result='draw'
}
}else if(user ==2){
if(com==3){
result='win';
}else if(com==2){
result='draw';
}else{
result='lose'
}
}else if(user ==3){
if(com==1){
result='win';
}else if(com==3){
result='draw';
}else{
result='lose'
}
}else{
alert('똑바로 입력해주세요')
}
return result;
}
console.log(result);
window.onload=function(){
document.getElementById("com").innerHTML=result;
}
alert(result)
과제2 - 퀴즈 문제 맞추기 게임
- 약 20개 이상의 문제를 미리 등록
- 미리 등록한 문제 중 3개를 출력하고 몇개 맞았는지 확인
- 3개 모두 맞추지 못할 경우 재시험
- (단, 1문제씩 출력하며 답을 전송 후 3초 후에 다음 문제가 출제)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="quiz2.js"></script>
</head>
<body>
<p id="com" > </p>
</body>
</html>
// 2. 퀴즈 문제 맞추기 게임을 작성
// - 약 20개 이상의 문제를 미리 등록
// - 미리 등록한 문제 중 3개를 출력하고 몇개 맞았는지 확인
// - 3개 모두 맞추지 못할 경우 재시험
// (단, 1문제씩 출력하며 답을 전송 후 3초 후에 다음 문제가 출제)
/*
1. 문제객체
key : 문제번호 q#
value : 배열[문제,답]
*/
const Question ={
q1 : ["5 + 7 = ?", 5+7],
q2 : ["6 + 4 = ?", 6+4],
q3 : ["10 + 50 = ?", 10+50],
q4 : ["1 + 5 = ?", 1+5 ],
q5 : ["4 + 7 = ?", 4+7],
q6 : ["12 + 3 = ?", 12+3],
q7 : ["7 + 5 = ?", 7+5],
q8 : ["8 + 2 = ?", 8+2]
}
//2. 배열 무작위 정렬 함수
function shuffle(array) {
for (let index = array.length - 1; index > 0; index--) {
// 무작위 index 값을 만든다. (0 이상의 배열 길이 값)
const randomPosition = Math.floor(Math.random() * (index + 1));
// 임시로 원본 값을 저장하고, randomPosition을 사용해 배열 요소를 섞는다.
const temporary = array[index];
array[index] = array[randomPosition];
array[randomPosition] = temporary;
}
}
//3. 문제출제함수
function func(a, b, c) {
setTimeout(() => {
user.push(prompt(a))
if(user[0]==threeA[0]) point++;
setTimeout(() => {
user.push(prompt(b))
console.log('2')
if(user[1]==threeA[1]) point++;
setTimeout(() => {
user.push(prompt(c))
console.log('3')
if(user[2]==threeA[2]) point++;
if(point==3){
alert('만점! 합격입니다');
document.getElementById("com").innerHTML='<h1>축하합니다! 합격입니다</h1>';
}
else{
alert(`${point}개 맞았습니다. 재시험입니다`);
user = [];
point = 0;
shuffle(arr);
threeQ=[arr[0][1][0],arr[1][1][0],arr[2][1][0]];
threeA=[arr[0][1][1],arr[1][1][1],arr[2][1][1]];
func(threeQ[0],threeQ[1],threeQ[2]);
}
}, 3000);
}, 3000);
}, 0);
}
let arr = Object.entries(Question); //object의 엔트리값들을 배열로 받기
shuffle(arr); //섞기
let threeQ=[arr[0][1][0],arr[1][1][0],arr[2][1][0]]; //문제 3개요소
let threeA=[arr[0][1][1],arr[1][1][1],arr[2][1][1]]; //정답 3개요소
let user=[]; //user작성답안
let point=0;
let re=0;
func(threeQ[0],threeQ[1],threeQ[2]);
'웹 개발 > 🌐 JavaScript' 카테고리의 다른 글
JavaScript | classList,dataset,map (1) | 2022.11.17 |
---|---|
JavaScript | promise,async,json,fetch (0) | 2022.11.17 |
JavaScript | 이벤트타입,이벤트리스너,이벤트객체,이벤트전파,iterable,generator,spread,set,map,operator (0) | 2022.11.11 |
JavaScript | 함수,오브젝트,클래스,상속,래퍼객체 (0) | 2022.11.09 |
JavaScript | history,navigator,dom,node,정규표현식 (1) | 2022.11.08 |