탬플릿 리터럴(Template Literal)
ES6부터 새로 도입된 문자열 표기법
문자열 생성 시 따옴표 대신, 백틱(`)을 사용
줄 바꿈, 표현식 삽입 가능
// 백틱(`)으로 줄바꿈 표현
const str_01 = `
Hi!
It's me!
JavaScript!
So Cool!`;
// ${} 사이에 변수, 연산 등 삽입 가능
const name = `사과`
const price = 100
const num = 5;
console.log(`${name}의 구매가는 ${price * num}원 입니다.`) // 사과의 구매가는 500원 입니다.
console.log(`${5+10} 입니다`) // 15 입니다
호이스팅
코드가 실행하기 전 변수/함수선언이 해당 스코프의 최상단으로 끌어올려진 것 같은 현상
코드 실행보다 먼저 메모리에 저장되는 과정으로 인한 현상
자바스크립트 엔진은 코드를 실행하기 전 실행 가능한 코드를 형상화하고 구분하는 과정(실행 컨텍스트를 위한 과정)을 거침
자바스크립트에서는 타입이 런타임시에(실행될 때) 결정된다
// 호이스팅 때문에 선언이 끌어올려져서 오류 안남.
console.log(text); // (선언 + 초기화 된 상태)
text = "Hanamon!"; // (선언 + 초기화 + 할당 된 상태)
var text;
console.log(text);
// 호이스팅 때문에 선언이 끌어올려졌지만 초기화 안된 상태에서 참조해서 오류 남.
// console.log(text); -> 선언 된 상태, 초기화(메모리 공간 확보와 undefined로 초기화) 안되서 참조 불가능 -> 에러
// let text; -> 여기서 초기화 단계가 실행됨
// const text; -> 에러, const 키워드로 재할당 불가(선언과 초기화 따로 작성 불가!)
const text1 = "default";
// text1 = "hananmon" //재할당 불가능
console.log(`text의 값은 ${text} 입니다.`);
const 변수명 = "테스트";
console.log(변수명);
// 변수: 특정 데이터 값을 임시로 저장하는 공간
// -> 특정 값을 자주 사용해야할 때
// -> 반복적인 구문(값)이 여러 코드에 걸쳐서 빈번히 쓰일 때
// 변수 선언 방식
// ES5 - var -> 호이스팅 이슈 발생
// ES6 - let, const사용, arrow function / ES7
// 변수 작성시 유의사항
// 숫자로 시작 불가, 특수문자(_, $) 불가, 예약어 불가, 대소문자 구분함
// 함수 선언문에서도 호이스팅이 일어난다
func1();
func2();
// func3(); -> 함수 표현식이라서 호이스팅이 일어나지 않는다
// 함수 선언문 1
function func1() {
console.log("func1 호출");
}
// 함수 선언문 2
function func2() {
console.log("func2 호출");
}
// 함수 표현식, 함수를 가리키는 변수를 선언하는 것(함수도 객체이니까)
const func3 = function () {
console.log("func3 호출");
};
func3(); // 함수 표현식이기에 여기서는 정상작동
// 함수
// 함수도 객체이다 - 함수도 파라미터로 넘길 수 있다
// 메소드 오버라이딩, 오버로딩에 대한 지원이 없다
// 같은 이름의 함수 중복정의 불가
text = "안녕"; // 선언이 없어도 에러없이 처리해줌 -> 선언이 없으면 var로 선언한 것과 동일함
var text;
// let text -> 선언이 없으면 let으로 정의했다 하더라도 에러
console.log(text);
/**
* 자료형(Data Type)의 종류
* 1. 원시형 자료(primative data type)
* 특정 값이 메모리에 저장됨
* -문자형([Object String])
* -숫자형(Number)
* -논리형(Boolean: true, false)
* -undefined: 변수를 선언하고 그 값을 초기화하지 않으면 undefined 저장됨(에러원인)
*
* 2. 참조형 자료(reference type)
* 값이 위치하고있는 참조 주소값만 메모리에 저장(관련 내장함수까지 같이 참조됨)
* -null(Object): 명시적으로 특정 변수의 값을 비워둘때
* -array(Object): 연관된 값들을 그룹으로 묶어 관리함 -> []
* -객체: Object 데이터를 key라는 인덱싱을 통해 자료를 구조적으로 묶어놓은 형태 -> {}
*/
/**
* false에 해당되는 것들
* 1) false
* 2) 0 - 0이 아닌 건 다 참 {}: Object, []:Array 참
* 3) null
* 4) undefined
* 5) NaN
* 6) ''빈문자열
*/
const dept = {
deptno: 10,
dname: "SALES",
loc: "CHICAGO",
boss: null,
};
console.log(dept); // { deptno: 10, dname: 'SALES', loc: 'CHICAGO' }
console.log(dept.dname); // SALES
console.log(dept.loc); // CHICAGO
console.log(dept["deptno"]); // 10
console.log(dept["year"]); // undefined
console.log(dept["boss"]); // null
// 객체: Object
// 데이터를 property라는 인덱싱을 통해 구조적으로 묶어놓은 형태
let car = {
name: "2023년형 소나타",
wheelNum: 4,
speed: 0,
carColor: "red",
};
console.log(car); // { name: '2023년형 소나타', wheelNum: 4, speed: 0, carColor: 'red' }
car.carColor = "black"; // 재할당 가능
console.log(
`내 자동차는 ${car.name}이고 바퀴수는 ${car["wheelNum"]}이고 색상은 ${car.carColor}입니다.`
);
// 내 자동차는 2023년형 소나타이고 바퀴수는 4이고 색상은 black입니다.
// 배열: Array
// 연관된 값들을 하나의 그룹으로 묶어서 나열한 자료구조
const colors = ["red", "green", "blue"];
const c1 = colors[0];
const c2 = colors[1];
const c3 = colors[2];
const { color1, color2, color3 } = colors;
console.log(colors); // [ 'red', 'green', 'blue' ]
console.log(c1); // red
// arr.filter(callback(element[, index[, array]])[, thisArg])
colors.filter(function (a, index, array) {
// 실행문
console.log(a);
console.log(index);
console.log(array);
// red
// 0
// [ 'red', 'green', 'blue' ]
// green
// 1
// [ 'red', 'green', 'blue' ]
// blue
// 2
// [ 'red', 'green', 'blue' ]
});
// 배열: Array
// 연관된 값들을 하나의 그룹으로 묶어서 나열한 자료구조
const colors = ["red", "green", "blue"];
console.log(colors); // [ 'red', 'green', 'blue' ]
// arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
// 함수의 이름이 없음 -> 사용자 호출이 불가함
colors.forEach(function (color, index, colors) {
console.log(color);
});
// red
// green
// blue
// arrow function으로 변경, 함수의 이름이 없음
colors.forEach((color, index, colors) => {
console.log(color);
});
// red
// green
// blue
// arrow function[ES6]에서는 파라미터가 한 개이면 괄호 생략 가능
colors.forEach(color => {
console.log(color);
});
// red
// green
// blue
// arrow function에서 실행문이 단일행일경우, 중괄호{} 생략 가능
colors.forEach(color => console.log(color));
// red
// green
// blue
const colors2 = ["red", "green",, "blue"];
console.log(colors2); // [ 'red', 'green', <1 empty item>, 'blue' ]
// 배열: Array Copy
// 얕은 복사(원본이 바뀜, 동기화)와 깊은 복사(복사본이 바뀜, 비동기)
const colors = ["red", "green", , "blue"];
const copy1 = [];
const copy2 = [];
const copy3 = [];
// 이전 방식
for (let i = 0; i < colors.length; i++) {
copy1.push(colors[i]);
console.log(`copy1[${i}]: ${copy1[i]}`);
// copy1[0]: red
// copy1[1]: green
// copy1[2]: undefined
// copy1[3]: blue
}
// 이후 방식
colors.forEach(function (color) {
copy2.push(color);
console.log(`${copy2}`);
// red
// red, green
// red, green, blue
});
["red", "green", "blue"].forEach((color) => {
copy3.push(color);
});
console.log(copy3);
// [ 'red', 'green', 'blue' ]
함수
자주쓰는 실행 코드들을 블록 단위({}단위)로 묶어서 패키징 해놓은 상태
자주 쓰는 코드들을 기능 단위로 재사용하기 위함
파라미터로 함수를 넘길 수 있다(자바와 다른 점)
함수 선언
function 예약어를 이용해 자주 사용할 코드를 묶음
함수 호출
정의된 함수를 호출해야 기능이 실행됨
함수의 종류
선언적 함수
이름을 가짐
자바스크립트 파일을 읽을 때 선언적 함수를 가장 먼저 읽어줌
호출 위치가 자유로움
익명 함수
함수의 이름이 없는 형태(대표적으로 콜백함수)
자체만으로 호출 불가
변수에 익명함수를 대입 또는 특정 이벤트 객체에 대입하는 형태로 호출함
대입 함수
변수에 익명함수가 대입된 형태
즉시실행함수
카카오 API의 지도서비스 코드
함수가 자기 자신을 정의하자마자 즉시 호출, 실행
(function () {
const a = 1;
const b = 2;
console.log(a + b);
})(); // 끝에 ()를 붙여줌 -> 즉시실행함수
// 첫()는 함수의 정의부, 두번째 ()는 함수의 호출부
/*
즉시실행함수
자기 자신을 정의하자마자 바로 자신을 호출하는 함수
첫번째 괄호는 함수의 선언부
두번째 괄호는 함수 호출 부분
*/
//이름이 있는 함수
function func1() {
console.log("func1");
func2(func1);
}
// 호출을 해야 함수가 실행됨
func1();
// func1
// [Function: func1]
// 파라미터로 함수를 받을수도 있다
function func2(func1) {
console.log(func1);
}
<!DOCTYPE html>
<html lang="ko">
<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 defer src="./main.js"></script>
</head>
<body>
</body>
</html>
// 리턴도 사용 가능
function hap(no1, no2) {
const result = no1 + no2;
return result;
}
const tot = hap(1, 2);
console.log(tot); // 3
<!DOCTYPE html>
<html lang="ko">
<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 defer src="./test.js"></script>
</head>
<body>
<!-- ul>li{버튼$}*3 자동완성 -->
<ul>
<li>버튼1</li>
<li>버튼2</li>
<li>버튼3</li>
</ul>
</body>
</html>
const lis = document.querySelectorAll("ul li"); // 같은 이름이면 브라우저가 자동으로 배열로 전환해줌
// 호이스팅이 발생해서 모두 3만 출력된다
// for문 안에서만 유지가 되어야 하는데, 밖에서도 유지됨
for (var x = 0; x < lis.length; x++) {
lis[x].addEventListener("click", function () {
console.log(x); // var는 호이스팅때문에 3만 찍힘
});
}
// 위의 var를 사용한 for문을 즉시실행함수로 바꾸기
// 특정한 원하지 않는 공간으로 그 값이 빠져나가지 못하게함
for (var x = 0; x < lis.length; x++) {
((index) => {
lis[x].addEventListener("click", () => {
console.log(index); // 0, 1, 2가 찍힘
});
})(x);
}
for (let x = 0; x < lis.length; x++) {
lis[x].addEventListener("click", () => {
console.log(x); // let으로하면 0, 1, 2가 찍힘
});
}
(function (x) {
const no1 = 1;
const no2 = 2;
console.log(no1 + no2 + x); // 8
})(5); // 파라미터 x가 있으니 값 넣어줌
// 즉시 실행 함수를 사용하는 이유
// 특정 원하지 않는 영역으로 그 값이 빠져나가지 못하게 할 때
// 즉시 실행 함수 내부의 값을 캡슐화할 때
// 파라미터 자리는 꼭 일치하지 않더라도 정상적으로 호출됨
// 파라미터로 넘긴 값은 함수 내부에서 사용 가능함
// Arrow Function 예제 1
let myFunction1 = function (x, y) {
return x * y;
};
let myFunction2 = (a, b) => a * b;
console.log(myFunction1(2, 6)); // 12
console.log(myFunction2(5, 6)); // 30
// Arrow Function 예제 2
let hello1 = function () {
return "Hello World!1";
};
let hello2 = () => {
return "Hello World!2";
};
console.log(hello1()); // Hello World!1
console.log(hello2()); // Hello World!2
let colors = ["red", "green", "blue"];
// 콜백함수 - 함수를 호출할 때 인수(파라미터)로 함수가 들어가는 형태
// arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
// ES5-반복처리기능, 유사배열도 처리해줌 / ES6-순수배열만
// 이전 버전, 파라미터 뒤의 두개(index, items)는 생략가능
// 3번 반복됨(배열의 길이만큼)
colors.forEach(function (color, index, items) {
console.log(color); // red green blue
console.log(index); // 0 1 2
console.log(items); // [ 'red', 'green', 'blue' ]
// red
// 0
// [ 'red', 'green', 'blue' ]
// green
// 1
// [ 'red', 'green', 'blue' ]
// blue
// 2
// [ 'red', 'green', 'blue' ]
});
// 이후 버전(arrow function) - React에서 자주나옴, 데이터가 변하면 변하는 것만 렌더링 처리함
colors.forEach((color) => {
console.log(color); // red green blue
// red
// green
// blue
});
// map사용
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
colors.map(function (color, index, items) {
console.log(color); // red green blue
console.log(index); // 0 1 2
console.log(items); // [ 'red', 'green', 'blue' ]
});
// 배열 내장 함수
const colors = ["red", "green", , "blue"];
console.log(colors); // [ 'red', 'green', <1 empty item>, 'blue' ]
// toString(): 배열을 문자로 변환
let result = colors.toString();
console.log(typeof result); // string
// join(): 배열의 모든 요소를 연결해 하나의 문자열로 만듦
result = colors.join("+"); // 파라미터 생략하면 ,로 구분
console.log(result); // red+green++blue
// pop(): 배열의 마지막 요소를 제거, 리턴값으로 잘라낸 요소 반환
result = colors.pop();
console.log(result); // blue
console.log(colors); // [ 'red', 'green', <1 empty item> ]
// push(): 배열의 끝부분에 새로운 요소 추가, 리턴값으로 배열의 길이 반환
result = colors.push("yellow");
console.log(result); // 4
console.log(colors); // [ 'red', 'green', <1 empty item>, 'yellow' ]
// shift(): 배열의 첫 부분 요소 제거, 리턴값으로 잘라낸 요소 반환
result = colors.shift();
console.log(result); // red
console.log(colors); // [ 'green', <1 empty item>, 'yellow' ]
// unshift(): 배열의 첫 부분에 새로운 요소 추가, 리턴값으로 배열의 길이 반환
result = colors.unshift("kiwi");
console.log(result); // 4
console.log(colors); // [ 'kiwi', 'green', <1 empty item>, 'yellow' ]
// splice(삽입할 위치, 잘라낼 개수, 추가할 내용): 배열에 새로운 요소를 잘라서 붙임
colors.splice(1, 0, "black");
console.log(colors); // [ 'kiwi', 'black', 'green', <1 empty item>, 'yellow' ]
// comcat(): 두 개의 배열 합치기
const color2 = ["cyan", "brown"];
result = colors.concat(color2);
console.log(result); // [ 'kiwi', 'black', 'green', <1 empty item>, 'yellow', 'cyan', 'brown' ]
// slice(): 배열 잘라내기 - 새로운 배열을 만들어서 잘라냄(리액트 CRUD처리시 자주 사용), 원본 배열은 그대로
result = colors.slice(1);
console.log(result); // [ 'black', 'green', <1 empty item>, 'yellow' ]
result = colors.slice(1, -1);
console.log(result); // [ 'black', 'green', <1 empty item> ]
<!DOCTYPE html>
<html lang="ko">
<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>배경이미지1</title>
<style>
* {
border: 1px solid red;
}
body {
height: 3000px;
}
div {
width: 500px;
height: 800px;
background-color: aquamarine;
/* background-color: transparent; */
background-repeat: no-repeat;
/* contain: 비율 유지, 요소의 더 짧은 너비에 맞춤 */
/* cover: 비율유지, 요소의 더 넓은 너비에 맞춤 */
/* auto: 이미지 실제 크기 */
background-size: auto;
background-image: url("../../images/sample/apple_280x280.jpg");
/* background-position: center; */
/* 스크롤은 되는데 이미지는 고정 */
background-attachment: fixed;
}
</style>
</head>
<body>
<div></div>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Atque aliquid
aut magnam alias! Molestiae impedit temporibus, necessitatibus itaque
numquam dolor!
</p>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<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>
<style>
.container {
width: 300px;
height: 300px;
background-color: aquamarine;
/* 자식태그가 부모태그 기준으로 그 안에서 움직이게 하려면 relative 줘야함 */
position: relative;
}
.container .item:nth-child(1) {
width: 100px;
height: 100px;
background-color: brown;
}
.item:nth-child(2) {
width: 140px;
height: 70px;
background-color: blue;
top: 30px;
right: 30px;
position: absolute; /* 자신의 위치를 기준으로 지정함 */
}
.item:nth-child(3) {
width: 70px;
height: 120px;
background-color: black;
}
</style>
</head>
<body>
<!-- div.container>div.item{$}*3 자동완성 -->
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<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>
<style>
.wrap {
width: 500px;
height: 500px;
background-color: tomato;
/* 부모 relative를 어디에 주느냐에 따라 자식태그 위치 달라짐 */
position: relative;
}
.container {
width: 300px;
height: 300px;
background-color: aquamarine;
}
.container .item:nth-child(1) {
width: 100px;
height: 100px;
background-color: brown;
/* z-index를 주려면 position이 지정되야한다 */
position: relative;
z-index: 3;
}
.item:nth-child(2) {
width: 100px;
height: 100px;
background-color: blue;
top: 50px;
left: 30px;
position: absolute;
z-index: 2;
}
.item:nth-child(3) {
width: 100px;
height: 100px;
background-color: black;
color: white;
position: relative;
z-index: 1;
}
</style>
</head>
<body>
<div class="wrap">
<!-- div.container>div.item{$}*3 자동완성 -->
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
</div>
</body>
</html>
<!--
position: 요소의 위치 지정 기준
static - 기준없음
relative - 요소 자신을 기준으로 함(이것을 기준으로 하는 배치 거의 사용안함, 아래와 같이 사용될때 부모요소)
absolute - 위치상 부모 요소를 기준 -> 위치상 부모요소를 꼭 확인해야함
fixed - 뷰포트(보통 브라우저의 크기) 기준
요소의 각 방향별 거리 지정
top, bottom, left, right 사용
auto - 브라우저가 자동으로 계산해줌
단위 - px(반응형에서 사용안함), em, rem
상대적인 값으로 줄 때 -> % 사용
-->
<!DOCTYPE html>
<html lang="ko">
<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>디자인 - A안</title>
<script
src=""
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="./index.css" />
</head>
<body>
<!-- 소개 및 탐색에 도움을 주는 콘텐츠틑 header에 담음 -->
<header>
<div class="container">
<h1>
<img src="../../images/home-solid.svg" width="50px" height="50px"></img></h1>
<nav class="main-navigation">
<a href="#">HTML</a>
<a href="#">CSS</a>
<a href="#">JAVASCRIPT</a>
<a href="#">REACT</a>
<a href="" class="btn">문의하기</a>
</nav>
</div>
</header>
<!-- 문서<body>의 주요 콘텐츠를 main에 담음 -->
<main class="main_bg">
<div class="video-wrap">
<video src="../../images/forest.mp4" muted autoplay loop></video>
</div>
<div class="container">
<div class="text-wrap">
<h2>MVC패턴<br>계층형게시판</h2>
<h3>JAVA + Servlet + JSP + Spring</h3>
<h3>HTML5 + CSS3 + JavaScript + React</h3>
<p>Front-End에서 부터 Back-End까지<br>풀스택 개발자를 양성하는 강좌입니다</p>
<div class="btn-wrap">
<a href="#" class="btn">강좌 등록하기</a>
<a href="#" class="btn ghost-btn">가입하기</a>
</div>
</div>
</div>
</main>
</body>
</html>
* {
box-sizing: border-box;
}
body {
background-color: black;
}
header {
top: 0;
left: 0;
width: 100%;
padding: 20px 0px;
position: absolute;
z-index: 2;
}
header h1 {
height: 40px;
margin: 0px;
float: left;
}
header h1 img {
display: block;
top: 10px;
background-color: white;
}
a {
font-size: 16px;
text-decoration: none;
}
.main-navigation {
float: right;
}
.main-navigation a {
color: white;
margin-left: 20px;
}
.btn {
display: inline-block;
font-weight: bold;
padding: 12px 20px;
background-color: darkcyan;
border-radius: 8px;
}
/* 가입, 등록버튼 */
.btn-wrap a {
background-color: darkcyan;
color: white;
}
/* 내용 처리 */
.main-bg {
position: relative;
width: 100%;
height: 100vh;
}
.video-wrap {
position: absolute;
left: 0;
width: 100%;
height: 100vh;
z-index: 1;
}
.container {
width: 100%;
max-width: 1480px;
padding: 0 20px;
margin: auto;
position: relative;
}
.text-wrap {
width: 520px;
height: 100vh;
padding: 240px 20px;
top: 0;
left: 0;
position: absolute;
z-index: 1;
}
.text-wrap h2 {
color: white;
font-size: 64px;
line-height: 1.25;
margin-bottom: 40px;
}
.text-wrap h3 {
color: white;
font-size: 24px;
line-height: 1.25;
margin-bottom: 20px;
}
.text-wrap p {
color: white;
font-size: 16px;
line-height: 1.8;
margin-bottom: 20px;
}
'국비학원 > 수업기록' 카테고리의 다른 글
국비 지원 개발자 과정_Day44 (0) | 2023.01.30 |
---|---|
국비 지원 개발자 과정_Day43 (1) | 2023.01.27 |
국비 지원 개발자 과정_Day41 (0) | 2023.01.25 |
국비 지원 개발자 과정_Day40 (0) | 2023.01.20 |
국비 지원 개발자 과정_Day39 (0) | 2023.01.19 |
댓글