카테고리 없음

[ChromeWeb] 공부 일지 1

히치키치 2021. 10. 1. 01:56

브라우저는 HTML을 열고, HTML은 CSS와 Js를 가져옴
const (상수) : 값 변경 불가능, 재선언 불가능, 기본적으로 사용

let : 값 변경 가능, 재선언 불가능, 필요시 사용
var : 값 변경 가능, 재선언 가능, 거의 사용 안 함

null : 변수 선언됨, "값이 없다"가 할당됨
undefined : 변수 선언됨 , 값이 할당되지 않음

array

//선언
const daysOfWeek=["월","화","수","목","금","토"]; 
const dateOfWeek=[1,2,"수","목",5];

//추가
daysOfWeek.push("일")

//요소 뽑기 (zero-indexing)
console.log(daysofWeek[0])

object : property를 가진 데이터, { } 사용

const player={
    name:"ayeon",
    point:10,
    fat:false,
};

//show object's property value
console.log(player)
console.log(player.name)
console.log(player["name"])

//change property value
player.fat=true //change Boolean value
console.log(player.fat)
player.point+=15 //change numerical value by cal-
console.log(player.point)

//add property and its value
player.lastName="ayeon"
console.log(player)

property value : 변경 0, object : 변경 X

array : 각 원소에 대한 설명 필요하지 않은 데이터

object : 각 원소에 대한 설명 필요한 정보가 담긴 데이터

 

Function

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

}
sayHello("nico",20)
sayHello("ayeon",40)
sayHello("yummy",90)

function plus(FirstNum,SecondNum){
    console.log(FirstNum+SecondNum)
}
plus(1,7)
plus(-1,1)
plus(6*4,10)

function divide(FirstNum,SecondNum){
    console.log(FirstNum/SecondNum)
}
divide(10,5)
divide(1,5)
divide(3,2)

Function with Object

const player_1={
    name:"nico",
    sayHello:function(otherPersonName){
        console.log("hello! "+ otherPersonName);
    },
    
};

console.log(player_1.name)
player_1.sayHello("ayeon");

Returns

const age=20;
function calculateKrAge(ageofForegineer){
    //ageofForegineer+=2
    return ageofForegineer+2
}

const KrAge=calculateKrAge(64);
console.log(KrAge)


const calculator={
    plus:function(a,b){
        return a+b
    },
    subtract:function(a,b){
        return a-b
    },
    multi:function(a,b)
{
    return a*b
}}

const plusResult=calculator.plus(10,4)
const subResult=calculator.subtract(10,4)
const multiResult=calculator.multi(10,4)

return까지만 코드 수행됨

 

자료형변환

prompt : 사용자에게 알림 팝업 창 띄움

typeof : 변수의 type 알려줌

parseInt() : string에서 number로 형변환

prompt 창에 숫자 입력시, parseInt가 string으로 들어온 숫자를 number로 바꿔줌

prompt 창에 문자/글 입력시, parseInt가 NaN을 띄움

 

const age=prompt("how old are you")
console.log(age)
//prompt get input as string
console.log(typeof age) 
 //parseInt change string to Int
console.log(parseInt(age))

parseInt() vs Number()

parseInt() : 숫자가 아닌 글자 만나면 그 이후 글자들 무시하고 해당 지점까지 int값 return

Number() : 숫자가 아닌 경우 NaN 변환

const a=Number("123ads123")
console.log(a) //NaN
const b=parseInt("123asd123")
console.log(b) //123

 

Conditional

 

== :  값만 비교

=== : 유형과 값 비교

&& : and 연산자 : 둘 다 true일 때 true임

|| : or 연산자 : 적어도 한 개가 true일 때 true임

isNaN(x) : 전달된 인수 x가 NaN인지 판별

 

1. 사용자 age 입력

      1-1. 입력한 것이 숫자가 아닌 경우, 다시 age 입력 요청

2. age로 음주 가능 여부 판정

const age1=parseInt(prompt())
if (isNaN(age1) || age1<0){
    console.log("Plz write a real positive number");
}
else if(age1<18){
    console.log("You are too young");
}
else if (age1>=18 && age1<=50){
    console.log("You can drink");
}
else if (age1>50 && age1<=80){
    console.log("You should exercise");
}
else if (age1===100){
    console.log("wow you are wise");
}
else if (age1>80){
    console.log("you can do whatever you want");
}

 

Js는 HTML과 연결되어 Js로 HTML을 불러오고 수정할 수 있음

 

DOM (Document Object Model) : 웹 문서의 모든 요소를 자바 스크립트를 이용해 조작할 수 있도록 객체를 사용해 문서를 해석하는 방법

브라우저에서 사용 가능한 document인 object

 

getElementByID : id 값은 DOM 내에서 고유/유일한 값으로 해당 아이디에 맞는 HTML 찾아줌

//1. 가져오기
const title=document.getElementById("title");
console.log(title)

//2. 값 변경
title.innerText="Got You"
console.log(title)

 

querySelector : CSS 선택자 방식으로 가져옴 but 오직 한개만 return

querySelectorAll : CSS 선택자에 해당하는 모든 것을 return

const title= document.querySelector(“.hello h1”);
const title= document.querySelectorAll(“.hello h1”);

 

getElementsByClassName : class 선택자는 여러번 사용 가능해 해당하는 모든 것을 가져와 array로 return

const hellos = document.getElementsByClassName(“hello”);

getElementsByTagName :  id와 class 선택자가 없는 경우 HTML 태그를 이용해 접근해 해당하는 모든 것을 가져와 array로 return

const title= document.getElementTagName(“h1”);

 

Js 이용해 html 요소 가져옴

console.dir() : object로 element의 내부 보여줌

console.dir(title)

on으로 시작하는 속성 모두 event임

addEventListener(이벤트, 함수) :

어떤 event 포착해야하는지.
해당 event 발생시 어떤 callback 함수 실행해야하는지

const title1=document.querySelector(".hello h1")
console.log(title1)
title1.style.color="blue"

//1. set which subject and event you are caring for
//2. make function which operate with event occuring
//3.  make them into addEventListener
//function that is included in addEventlistner is called "callback function"

function handleTitleClick(){
    console.log("title was clicked!");
    title1.style.color="pink"
}
title1.addEventListener("click",handleTitleClick)
const title2=document.querySelector("div.hello h1")
console.log(title2)


function handleMouseEnter(){
    title2.innerText="Mouse is here!"
}

function handleMouseLeave(){
    title2.innerText="Mouse is gone!"
}

title2.addEventListener("mouseenter",handleMouseEnter)
title2.addEventListener("mouseleave",handleMouseLeave)

 

addEventListener의 또 다른 표기법

//title1.addEventListener("click",handleTitleClick)
title1.onclick=handleTitleClick; 

//title2.addEventListener("mouseenter",handleMouseEnter)
title2.onmouseenter=handleMouseEnter;

//title2.addEventListener("mouseleave",handleMouseLeave)
title2.onmouseleave=handleMouseLeave;

 

window와 관련된 event

function handleWindowResize(){
    document.body.style.backgroundColor="red";
}
function handleWindowCopy(){
    alert("Copier!!");
}
window.addEventListener("resize",handleWindowResize)
window.addEventListener("copy",handleWindowCopy)

 

wifi와 관련된 event

function handleWindowOffline(){
    alert("SOS!! NO WIFI");
}

function handleWindowOnline(){
    alert("Good!! WIFI Connected");
}

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

Event with style change in HTML

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

function handleTitleClick(){
    const currentColor=h1.style.color;//get color
    let newColor;

    if (currentColor==="blue"){
        newColor="tomato";//set color
    }
    else{
        newColor="blue";
    }
    h1.style.color=newColor;
}

function handleMouseEnter(){
    h1.innerText="Mouse is here!";
}
h1.addEventListener("click",handleTitleClick)