https://jjun7983.tistory.com/226

 

c# 0 채우기 문자열 , 특정 문자 채우기

c# 으로 문자열 앞에 0을 채워야 할 경우가 있고... 특정 문자를 채워야 할 때가있다... 이럴때 PadLeft 또는 PadRight 를 사용하면 된다. 사용 방법 string str = "test"; char pad = '0'; str.PadLeft(전체 자..

jjun7983.tistory.com

 

preventDefault() (Function과 Event의 동작)

  • 공통점 : 실행시 EventArgument Object를 넣어줘서 실행시킨다.
  • 차이점 : 넣어주는 타이밍이 다르다. Function은 브라우저가 즉시 EventArgument Object를 ( )에 넣어 줘서 자동으로 실행하고 Event는 동작활성화 때 EventArgument Object를 ( )에넣어 줘서 실행시킨다.

예시

// HTML 일부
<form id="login-form" class="hidden">
	<input required maxlength="15" type="text" placeholder="What is your name?" />
    <input type="submit" vale="Log In" />
</form>
<h1 id="greeting" class="hidden"></h1>

 

/* JS */
const loginForm = document.querySelector("#login-form");
const loginInput = document.querySelector("#login-form input");
const greeting = document.querySelector("#greeting");

const HIDDEN_CLASSNAME = "hidden";
const USERNAME_KEY = "username";
const savedUsername = localStorage.getItem(USERNAME_KEY);

function onLoginSubmit(event){
	const username = loginInput.value;
    event.preventDefault();	//form의 기본submit 기능을 멈춘다
    //console.dir(event);
    
    loginForm.classList.add(HIDDEN_CLASSNAME);
    paintGreeting(username);
    
    localStorage.setItem(USERNAME_KEY, username); //localStorage라는 DB를 활용
}


//onLoginSubmit();

if(savedUsername === null){
	loginForm.classList.remove(HIDDEN_CLASSNAME);
    loginForm.addEventListener("submit", onLoginSubmit);
}else{
	paintGreeting(savedUsername);
}

function paintGreeting(name){
	greeting.innerText = `Hello ${name}`;	//c#에서는 $"Hello {name}"로 사용
    greeting.classList.remove(HIDDEN_CLASSNAME);
}

 

 

localStorage

  • 브라우저에 기억할 수 있게 하는 API / 미니 DB같은 느낌
  • 예시는 위에 같이
  • 자주 사용하는 함수 : localStorage.getItem(KEY) / localStorage.setItem(KEY, value)

 

 

문자열보간(C#과 비교)

`Hello ${name}`;  <==>  $"Hello {name}";

  - 문자열보간을 쓰고 싶을 때 `(물결표시와 같이 있는 문자/그레이브)를 사용

 

 

Template literals - JavaScript | MDN

템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다. 이전 버전의 ES2015사양 명세에서는 "template strings" (템플릿 문

developer.mozilla.org

 

Element.ClassList

  • 역할 : CSS파일의 style의 설정들 중 class와 관련된 style을 적용 및 해제시키는 역할
  • css (html과 js의 속성을 적용할 때는 ""로 string으로 인식시켜야 하지만 css는 바로 쓴다)
  • 예제
<!-- CSS -->

h1{
	color: conrflowerblue;
    transition: color 0.5s ease-in-out;
}
/* JS */

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

function handleTitleClick(){
	const clickedClass = "clicked";
    
    if( h1.classList.contains(clickedClass) ){
    	h1.classList.remove(clickedClass);
    }else{
    	h1.classList.add(clickedClass);
    }
    
    //위 if문과 같이 2가지 경우만 존재할 경우
    //h1.classList.toggle("clicked");
    
}

h1.addEventListener("click", handleTitleClick);

JavaScript 사용하는 이유

  • HTML과 상호작용하기 위해 => HTML의 Element들을 JavaScript를 통해 변경하고 읽을 수 있음
  • JavaScript에서 대부분 작업할 일 : event를 listen하는 일

 

JavaScript에서 HTML element를 검색하는 방법

const title = document.getElementById("hello");

console.dir(title); //이를 통해 element의 object 구성을 볼 수 있다.

 

Document Object(객체)

  • Document 객체
    • 브라우저에 이미 존재하는 객체 => HTML을 가리키는 객체
    • JavaScript에서 자동으로 Document 객체를 통해 HTML에 접근해서 읽고 변경할 수 있음 => JavaScript와 HTML이 자동으로 연결되어 있음
  • Document 객체 확인하기
    • 브라우저에서 Console창에 dir(document)를 입력하면 작성된 HTML객체를 볼수 있음 => JavaScript관점에서 HTML document를 보여줌
    • Javascript에서는 console.dir(document); 을 입력하면 작성된 HTML객체를 볼 수 있음 => JavaScript관점에서 HTML document를 보여줌

 

Event

  • HTML
<!--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">
        <link rel="stylesheet" href="style.css">
        <title>EventTest</title>
    </head>
    <body>
        <div class = "EventTest">
            <h1>NoChange1</h1>
            <h1  id = "hello">Hello</h1>
        </div>
        <div class = "EventTest">
            <h1>NoChange3</h1>
            <h1>NoChange4</h1>
        </div>
        <script src="app2.js"></script>
    </body>
</html>
  • JavaScript(app2.js)
//*
const title = document.getElementById("hello");	//하나의 값으로 반환

//const title = document.getElementsByClassName("EventTest");	//array로 반환
//const title = document.getElementsByTagName("h1");//Tag : dir, anchor, section, button 등 / array로 반환

//***
//const title = document.querySelector("dir.EventTest:nth-child(2) h1:last-child");//css방식으로 검색

//const title = document.querySelector("#hello");//id검색 : #idName / class검색 : .className
//const title = document.querySelectorAll(".EventTest"); //Selector는 해당하는 처음값을 반환 / SelectorAll은 array로 해당하는 값들을 모두 반환

function handleTitleClick(){
	title.innerText = "Click Event";
	title.style.color = "blue";
}

function handleWindowResize(){
	document.body.style.backgroundColor = "tomato";
}

title.addEventListener("click", handleTitleClick);	//함수handleTitleClick의 ()는 실행하라는 역할 따라서, 필요할 때 부르는 event에서는 뺀다
//title.onClick = handleTitleClick;

window.addEventListener("resize", handleWindowResize);
//window.onResize = handleWindowResize;

 

Event찾는 사이트

https://developer.mozilla.org/en-US/docs/Web/API/Window

 

Window - Web APIs | MDN

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/Events

 

이벤트 참조 | MDN

DOM 이벤트는 발생한 흥미로운 것을 코드에 알리기 위해 전달됩니다. 각 이벤트는 Event 인터페이스를 기반으로한 객체에 의해 표현되며 발생한 것에 대한 부가적인 정보를 얻는데 사용되는 추가

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement

 

HTMLHeadingElement - Web APIs | MDN

The HTMLHeadingElement interface represents the different heading elements, <h1> through <h6>. It inherits methods and properties from the HTMLElement interface.

developer.mozilla.org

 

Function

  • 함수 생성
    • function nameOfFunc(arg1, arg2, ...){ return val; }
    • const player = {name: "Kim", age: 30, nameOfFunc: function(arg1, arg2, ...){ return val; }                          (object는 c#의 structure와 동일한 것 같음)
  • 함수 사용  
    • nameOfFunc(x, y);
    • player.nameOfFunc(x, y);

 

Contionals(조건문)

  • if문 구조
    • if(  ){ 
    • }else if(  ){ 
    • }else{  }

 

Equal연산자

  • == & != (c# ==, != 와 동일) : equal 연산자 : 이 같은지 비교
  • === & !== : strict equal 연산자 : 데이터타입이 같은지 비교
  • 차이점 예시(equal연산자 / strict equal연산자)
    • 1 ~ "1"                          => true / false
    • null ~ undefined              => true / false
    • true ~ 1                         => true / false
    • 0 ~ ""                            => true / false
    • NaN ~ NaN                    => false / false
    • a = [1, 2, 3] ~ b = [1, 2, 3] => false / false (값과 데이터 타입이 같지만 메모리주소가 다르기 때문)

 

그외

  • typeof : 뒤의 변수 타입을 반환하는 키워드 / 사용 : typeof val : val의 타입을 반환
  • parseInt(str) (c#의 Int.Parse(str)와 동일)
  • isNaN(val) : NaN인지 확인하는 함수

DataType

  • integer
  • float
  • string
  • null : 값이 없음, 아무것도 없는 상태로 채움, 채워져 있음
  • undefined : 메모리에는 존재 but 채워져 있지 않음
  • boolean : true, flase ( 주의!!  Python의 boolean : True, False)
  • NaN (Not a Number)

 

Variable 생성

  • 키워드
    • const : 상수 선언, 기본적으로 변수 선언시 사용 (참고 : object에서 데이터구조가 바뀌지 않아도 속성값만 변경, 추가하는 것은 허용 & 변수를 업데이트할 경우가 거의 없음 => 기본적으로 사용하게 되지 않았을까 싶음)
    • let : 변수 선언
    • var : 앞으로 사용X

 

Array

  • 특징 : 가장 기본적인 데이터 구조
  • 예시 : const array = [1, 2, 3, 4];
  • Console.log(array[3]);
  • 원소 추가 : array.push(5);
  • 함수(정렬하기 : array.sort();
    • Array합치기
      1. const newArray = [1, 2, 3].concat([4, 5], [6, 7, 8]);   //기존 [1, 2, 3]가 변경되지 않는다 참조주소가 바뀌지 않는다
    • Array요소들을 하나의 문자열로 만들기
      1. ['Shane', 'Alan', 'Osbourne'].join();  => return : Shane,Alan,Osbourne
      2. Array.join('_'); => return : Shane_Alan_Osbourne
    • 요소의 위치 찾기
      1. ['Shane', 'Sally', 'Isaac'].indexOf('Isaac'); => return : 2 
      2. ['Shane', 'Sally', 'Isaac'].indexOf('Isaac', 2); => return : -1 // 해당 값이 존재하지 않을 경우 -1 반환
      3. [{ name: 'Shane' }, { name: 'Sally' }, { name: 'kittie' }].indexOf(kittie)); => return : 2 // 요소가 object일 때
    • Array 부분복제
      1. const copyArray = [1, 2, 3, 4, 5].slice(); => return : copyArray = [1, 2, 3, 4, 5]
      2. const copyArray = [1, 2, 3, 4, 5].slice(2, 3); => return : copyArray = [3]
      3. const copyArray = [1, 2, 3, 4, 5].slice(2); => return : copyArray = [3, 4, 5]
      4. const copyArray = [1, 2, 3, 4, 5].slice(-2); => return : copyArray = [4, 5]
      5. const copyArray = [1, 2, 3, 4, 5].slice(1, -1); => return : copyArray = [2, 3, 4]
    • 요소를 제거하기   /  const prevArray= ['angel', 'clown', 'mandarin', 'surgeon'];
      1. const postArray = prevArray.splice(2, 1);  // prevArray = ['angel', 'clown', 'surgeon'] / postArray = ['mandarin']
      2. const postArray = prevArray.splice(2);  // prevArray = ['angel', 'clown'] / postArray = ['mandarin', 'surgeon']
      3. const popped = prevArray.pop();  //prevArray = ['angel', 'clown', 'mandarin'] / popped = 'surgeon'
      4. const shifted = prevArray.shift();  //prevArray = ['clown', 'mandarin', 'surgeon'] / shifted = 'angel'
    • 요소를 변경하기   /  const prevArray= ['angel', 'clown', 'mandarin', 'surgeon'];
      1. const postArray = prevArray.splice(1, 1, 'parrot'] ); // prevArray = ['angel', 'parrot', 'mandarin', 'surgeon'] / postArray = ['clown']
      2. const postArray = prevArray.splice(0, 2, 'parrot', 'trumpet'); // prevArray = ['parrot', 'trumpet', 'mandarin', 'surgeon'] / postArray = ['angel', 'clown']
    • 요소를 추가하기   /  const prevArray= ['angel', 'clown', 'mandarin', 'surgeon'];
      1. const postArray = prevArray.splice(1, 0, 'parrot'] ); // prevArray = ['angel', 'parrot', 'clown', 'mandarin', 'surgeon'] / postArray = []
      2. const postArray = prevArray.splice(1, 1, 'parrot', 'clown'); // prevArray = ['angel', 'parrot',  'clown', 'mandarin', 'surgeon'] / postArray = ['clown']
      3. prevArray.push('parrot', 'clown') => prevArray = ['angel', 'clown', 'mandarin', 'surgeon', 'parrot', 'clown']
      4. prevArray.push( ['parrot', 'clown'] ) => prevArray=['angel', 'clown', 'mandarin', 'surgeon', ['parrot', 'clown']]
      5. const unshifted = prevArray.unshift('parrot', 'clown') => prevArray=['parrot', 'clown', 'angel', 'clown', 'mandarin', 'surgeon'] / unshifted = 6 (동작후 prevArray의 length)
    • 정렬하기
      1. items = ['Shane', 'Sally', 'Isaacs'];   items.sort(); => return : items = ['Isaacs', 'Sally', 'Shane']
      2. items = [10, 30, 2, 20];  items.sort(); => return : items = [10, 2, 20, 30]
      3. <숫자 오름차순 정렬>items = [10, 2, 20, 30]; items.sort( (a, b) => a - b );  => return : items = [2, 10, 20, 30]
      4. <숫자 내림차순 정렬>items = [10, 2, 20, 30]; items.sort( (a, b) => b - a );  => return : items = [30, 20, 10, 2]
      5. items = ['Shane', 'Sally', 'Isaacs'];  items.sort( (a, b) => a.length - b.length ); => return : items = ['Sally', 'Shane', 'Isaacs']

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array

 

Array - JavaScript | MDN

JavaScript Array 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다.

developer.mozilla.org

 

 

Object

  • 예시 : const player = { name: "Kim", level: 1}; (속성값(name, level) 변경, 추가 가능)
  • Console.log(player.name); or Console.log(player["name"]);
  • 속성 추가 : player.lastName = "You";

 

 

JavaScript

  • 개발 : 브렌던 아이크(Brendan Eich)가 개발, 넷스케이프(브라우저)를 위해 탄생
  • 목적 : 인터렉티브(interactive)하게 만들기 위해
  • 장점 : 
    1. 프론트엔드로 쓸 수 있는 유일한 언어
    2. 모든 브라우저에 내장되어 설치할 필요 없음 => 접근성이 높음
    3. 프레임워크 활용으로 다양하게 사용
      • 리엑트 네이티브 : 모바일앱 제작
      • Electron : 웹앱 제작
    4. 다양한 라이브러리
      • Socket.io : 실시간 웹앱 제작
      • ml5.js(ml라이브러리) : 머신러닝

 

구조도

브라우저 ↔ HTML ← 마크업언어로 CSS와 JavaScript를 연결

CSS : <link rel = "stylesheet" href = "style.css" />

        href에서 css파일명을 입력해서 연결

JavaScript : <script src = "app.js"></script>

        src에 js파일명을 입력해서 연결

+ Recent posts