카테고리 없음

바닐라 JS 강의 이론 부분 정리 #1

에푸 2022. 5. 6. 12:23
// js 이론

 

 
// 일반적으로 변수선언 시 값의 변화를 줄 수 없는 const 사용, 값의 변화가 필요할 때(반복문 등) let 사용
// var는 사용하지 않음
// 변수선언 또는 함수사용 시 notAtAll 처럼 띄어쓰기되는 부분을 대문자로 처리하는 것이 관례
// python의 경우 not_at_all로 사용을 하는 것이 관례

 

// boolean (논리연산) true / false

const amIFat = true;
let something;

 

console.log(amIFat);
console.log(something); 

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// array배열 ( 대괄호 )                                                 
// C에서는 중괄호를 썼던 것과 다름
const daysOfWeek = ["mon","tue","wed","thu","fri","sat"];

 

console.log(daysOfWeek);
console.log(daysOfWeek[4]);

 

daysOfWeek.push("sun");

 

console.log(daysOfWeek);     

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// objects 구조체 ( 중괄호 )
const player = {
    name: "elfu",
    points: 1100,
    fat: true,
};
console.log(player);
console.log(player.name);
console.log(player["name"]);
player.fat = false;
console.log(player);
player.latsName = "potato";
console.log(player);
player.points = player.points + 15;
console.log(player.points); 

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================



// function 함수 사용 (매개변수의 자료형은 안 써도 됨) 
// 나중에 typescript에서는 c언어처럼 자료형을 쓰게 됨 

 

function sayHello(nameOfPerson, age) {
    console.log("Hello my name is " + nameOfPerson + " and I'm " + age)

 

}

 

sayHello("nico", 17);
sayHello("dal", 20);
sayHello("lynn", 21);

 

function plus(a, b) {
    console.log("계산값은 " + (a + b) + "입니다");
}
function divide(a, b) {
    console.log("계산값은 " + (a / b) + "입니다");
}

 

plus(1, 5);
divide(2, 5);

 

const player = {
    name: "elfu",
    hello: function(otherPersonName) {
        console.log("hello " + otherPersonName + " Nice to meet you!");
    },

 

}

 

player.hello("lynn");
player.hello("nico"); */

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// 계산기

 

/* const calculator = {
    add: function (a, b) {
        console.log("더하기의 결과는 " + (a + b) + "입니다");
    },
    minus: function (a, b) {
        console.log("빼기의 결과는 " + (a - b) + "입니다");
    },
    divide: function (a, b) {
        console.log("나누기의 결과는 " + (a / b) + "입니다");
    },
    mul: function (a, b) {
        console.log("곱셈의 결과는 " + (a * b) + "입니다");
    },
    powerOf: function (a, b) {
        console.log("제곱의 결과는 " + (a ** b) + "입니다");
    }
};

 

calculator.add(65537, 65537);
calculator.minus(154545, 35111);
calculator.divide(215548, 25499);
calculator.mul(215548, 25499);
calculator.powerOf(2, 20); */

 

const age = 96;
function calculateKrAge(ageOfForeigner) {
    return ageOfForeigner + 2;
}

 

const KrAge = calculateKrAge(age);

 

console.log(KrAge); */

 

/* const calculator = {
    add: function (a, b) {
        return a + b;
    },
    minus: function (a, b) {
        return a - b;    },
    divide: function (a, b) {
        return a / b;
    },
    mul: function (a, b) {
        return a * b;    },
    powerOf: function (a, b) {
        return a ** b;
    }
};

 

const plusResult = add(1, 2);
const minusResult = minus(1, 2);
const divideResult = divide(1, 2);
const mulResult = mul(1, 2);
const powerOfResult = powerOf(1, 2); */

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// if문

 

// 이건 내 해결방법 또는 or연산을 조건문에 삽입
function ads(a) {
    if (a < 0) {
        return a *= -1;
    } else {
        return a;
    }

 

}

// parseInt(): 문자열 숫자로 변환

let age = parseInt(prompt("How old are you?"));
age = ads(age);     // 절댓값으로 변환

// isNaN(): Not a Number 인자의 값이 숫자가 아니면 true(1) 숫자면 false(0) 반환

if (isNaN(age) == 1) {
    alert("숫자만 입력해주십시오");

 

    age = parseInt(prompt("How old are you?"));
} else if (age < 18) {
    alert("너무 어립니다");
} else if (age > 50 && age < 80) {
    alert("해당 술은 너무 독합니다");
} else if (age >= 18 && age <= 50) {
    alert("구매하실 수 있습니다!");
} else {
    alert("구매 불가!");
}

 

console.log(age);
//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

const cssit = document.querySelector(".hello h1");     
// class를 통해서 사용할 경우 .을 사용(hello class의 h1태그)
const cssid = document.querySelector("#second");      
 // id를 통해서 전달할 경우 #을 사용
const cssarray = document.querySelectorAll(".hello h1"); 
// hello class의 '모든' h1태그

 

cssit.innerText = "hello";

 

console.log(cssit);
console.log(cssid);
console.log(cssarray);



// html과 js는 연결되어 있다
// html에 적힌 id를 이용해 적용할 수 있다
// class와 id가 매우 중요하다
// * html에서 element들을 가지고와서 js를 통해 항목들을 변경한다
// getElementsById / ByClassName / ByTagName /  
>> 여기선 id를 통해서 전달할 경우 아무것도 쓰지 않아도 됨. (id가 기본방식)
// 대부분 querySelector 사용 (css 방식) 일반값 반환(id와 같음) >> (".(class명) (tag명)")
// querySelectorAll 사용 시 array 반환 ****



//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// Events ~! element를 찾고, eventlistener 추가, event발생 > 짠!
// MDN 참고! EX > h1 element mdn
const h1 = document.querySelector(".hello h1");

 

h1.style.color = "blue";

 

function handleh1Click() {
    if (h1.style.color == "blue") {
        h1.style.color = "red";
    } else if (h1.style.color == "red") {
        h1.style.color = "blue";
    }
}
function handleMouseEnter() {
    h1.innerHTML = "mouse is here!";
}
function handleMouseLeave() {
    h1.innerHTML = "mouse is gone!";
}
function handleWindowResize() {
    document.body.style.backgroundColor = "tomato";
}
function handleWindowCopy() {
    alert("copier!");
}
function handleWindowOnline() {
    alert("ALL GOOD!");
}
function handleWindowOffline() {
    alert("NO!");
}

 

h1.addEventListener("click", handleh1Click);
h1.addEventListener("mouseenter", handleMouseEnter);
h1.addEventListener("mouseleave", handleMouseLeave);

 

window.addEventListener("resize", handleWindowResize);
window.addEventListener("copy", handleWindowCopy);

 

window.addEventListener("online", handleWindowOnline);
window.addEventListener("online", handleWindowOffline);

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

// 위의 것 개선버전 일종의 swap algorithm 및 조건문
const h1 = document.querySelector(".hello h1");

 

console.log(h1.style.color);
function handleh1Click() {
    const correntColor = h1.style.color;
// if문이 시작되기 전 h1.style.color;의 값은 변경하지 않고 컬러값 변경하기 위해
    let newColor;                              // temp 역할
    if (correntColor == "blue") {
        newColor = "red";                               
// blue면 red로 바꾸고 
        console.log(h1.style.color);                   
// 현재 컬러인 blue 출력
    } else {                                               
// blue가 아니면
        newColor = "blue";                         
 // newColor에 blue를 넣고
        console.log(h1.style.color);                 
// blue가 아닌 것을 출력
    }
    h1.style.color = newColor;                     
// newColor에 있던 것을 h1.style.color에 최종 적용 다시 클릭 시                                                                  // 이 조건문이 돌아가면서 조건문 진행 동안 h1.style.color가 바뀌지 않고
}                                                         
// correntColor의 값을 기준으로 판단하고 원본 데이터는 보존                                                     
// correntColor를 굳이 사용하는 이유는 역할을 구분짓기 위해서도 있음
h1.addEventListener("click", handleh1Click); 
// addEventListener 사용 시 인자 함수에 ()넣지 않도록 조심할 것
// 이유는 ()가 들어가게 되면 이벤트와 상관없이 실행해야 되는 함수로 인식함
                

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================

 

const h1 = document.querySelector(".hello h1");

 

function handleTitleClick() {
    //const clikedClass = "clicked";
    /* if (h1.classList.contains(clikedClass)) {
        h1.classList.remove(clikedClass);
    } else {
        h1.classList.add(clikedClass);
    } */
    h1.classList.toggle("clicked");



}
// className은 기존에 있던 class를 지워버림
// 허나 classList.()는 classList에 해당클래스가 있는지
// contains로 검사하고, remove로 제거하고, add로 다시 추가해줄 수 있다
// 허나 이 과정은 toggle로 대체될 수 있다
h1.addEventListener("click", handleTitleClick);

 

//====================================================================================================================================
//====================================================================================================================================
//====================================================================================================================================



const loginForm = document.querySelector("#login-form");     // html에서 login-form id를 가져옴
const logininput = loginForm.querySelector("input");              // login-form에서 input태그 가져옴
//const loginButton = loginForm.querySelector("button");        
const greeting = document.querySelector("#greeting");           // html에서 greeting id 가져옴
//const greeting2 = document.querySelector("#greeting2");
//const link = document.querySelector("a");
const logoutForm = document.querySelector("#logout-form");

 

const HIDDEN_CLASSNAME = "hidden"; 
// css에서 .hidden { display: none; }을 설정하면
// hidden classname이 추가됐을 때 해당 태그를 안 보이게 설정 가능 이것을 이용해 js로 컨트롤
const USERNAME_KEY = "username";        
// 본인이 작성한 string이 반복될 경우 상수변수를 선언하여 오류를 발견할 수 있게 만든다

 

function onLoginSubmit(event) {
    event.preventDefault();
    loginForm.classList.add(HIDDEN_CLASSNAME);

 

    const username = logininput.value;
    localStorage.setItem(USERNAME_KEY, username);      
// username과 savedUsername의 역할이 다르다
    paintGreetings(username);                          
// 처음에 제출된 username의 paint함수는
// 유저가 직접 쳤을 때 임시로 저장되는 것을 나타내기 위한 변수
    logoutForm.classList.remove(HIDDEN_CLASSNAME);      
// if문에서 제출된 savedUsername의 paint함수는
// 이미 저장된 내용을 storage에서 불러온 것을 나타내기 위한 변수
    //greeting.innerText = "hello " + username;         // 두 가지 방법 중에 하나
    //greeting.classList.remove(HIDDEN_CLASSNAME);
    /* greeting2.innerText = `Hello ${username}`;
    greeting2.classList.remove(HIDDEN_CLASSNAME); */
/*     if (username === "") {
        alert("Please write your name");
    } else if (username.length > 15) {
        alert("your name is too long");
    } */
}

 

function paintGreetings(username) {
    greeting.innerText = `Hello ${username}`;
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

 

function logoutSubmit() {
    localStorage.removeItem(USERNAME_KEY);
    //window.location.reload();
}



/*
function linkClick(event) {
    event.preventDefault();
    console.dir(event);
   
} */

 

//loginForm.addEventListener("submit", onLoginSubmit);
/* link.addEventListener("click", linkClick); */

 

logoutForm.addEventListener("submit", logoutSubmit);

 

const savedUsername = localStorage.getItem(USERNAME_KEY);
if(savedUsername === null) {
    // show the form
    loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit", onLoginSubmit);
   
} else {
    // show the greetings
    paintGreetings(savedUsername);
    logoutForm.classList.remove(HIDDEN_CLASSNAME);
}