1. Css_RWD5_Image1.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Responsive Images</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--
https://www.w3schools.com/css/css_rwd_images.asp
https://www.w3schools.com/howto/howto_css_image_responsive.asp
-->
<style>
/* image 가 확대축소 되게 하려면 */
.responsive1 {
width: 100%;
height: auto;
}
/* image 가 축소는 될지언정, 화면이 커져도 이미지 '원래 크기' 이상 늘어나지 않게 하려면 */
.responsive2 {
max-width: 100%; /* 이미지 원래의 크기 100% 만큼이 최대치 */
height: auto;
}
/* image 를 특정 maximum 사이즈 이내로 국한시킬 경우 */
.responsive3 {
width: 100;
max-width: 400px; /* 최대 사이즈 */
}
</style>
</head>
<body>
<h2>Responsive Images</h2>
<p>브라우저 윈도우를 확대 축소 시켜서 확인해보세요</p>
<img src="../img/img_nature.jpg" alt="Nature" class="responsive1" width="600" height="400">
<br>
<img src="../img/img_nature.jpg" alt="Nature" class="responsive2" width="600" height="400">
<br>
<img src="../img/img_nature.jpg" alt="Nature" class="responsive3" width="600" height="400">
</body>
</html>
2. Css_RWD5_Image2.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RWD background image</title>
<!--
background-image 또한 크기에 따른 resizing 이 가능하다
-->
<style>
div {
width: 100%;
height: 400px;
border: 1px solid red;
background-image: url('../img/img_flowers.jpg');
background-repeat: no-repeat;
}
div#bg1 {
background-size: contain;
/*
background-size : contain
이미지의 종횡비(aspect ratio)는 유지된채 content 에
맞추어진다. content 에 빈 공간 발생 가능 (no-repeat 인 경우)
*/
}
div#bg2 {
background-size: 100% 100%;
/*
background-size: 100% 100%;
배경 이미지는 content 영역에 빈 공간 없이 가득 채워지게
좌우 꽉 채워지게 늘어난다(혹은 줄어든다)
*/
}
div#bg3 {
background-size: cover;
/*
background-size: cover;
배경 이미지는 content 영역을 가득 채우긴 하나
이미지의 종횡비가 유지된다. 이미지의 잘림(clip) 발생
*/
}
</style>
</head>
<body>
<p>브라우저 창 크기를 조정해보세요</p>
<h3>background-size: contain</h3>
<div id="bg1"></div>
<hr>
<h3>background-size: 100% 100%</h3>
<div id="bg2"></div>
<hr>
<h3>background-size: cover</h3>
<div id="bg3"></div>
</body>
</html>
3. Css_RWD5_Image3.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RWD : 다른크기 이미지</title>
<!--
PC에선 '대용량 이미지'로 보여주어도 관계 없으나, 모바일에는 부담된다.
따라서, media query 등을 사용하여 모바일 환경에서는 '저용량 이미지'로
바꾸어 보여주게 할수도 있다.
https://www.w3schools.com/css/css_rwd_images.asp
-->
<style>
/* For width smaller than 400px: */
body {
background-repeat: no-repeat;
background-image: url('../img/img_smallflower.jpg');
}
/* For width 400px and larger: */
@media screen and (min-width: 400px) {
body {
background-image: url('../img/img_flowers.jpg'); /* 출력이 안됨 */
}
}
</style>
</head>
<body>
<p style="margin-top:360px;">Resize the browser width and the background image will change at 400px.</p>
</body>
</html>
4. Css13_RWD6_SideBar.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SideBar</title>
<!--
700px 이상
700px ~ 400px 사이 일때
400px 이하 일때
서로 다른형태로 보이는 Side menu
-->
<style>
body {
margin: 0;
font-family: "Lato", sans-serif;
}
.sidebar {
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
.sidebar a {
display: block;
color: black;
padding: 16px;
text-decoration: none;
}
.sidebar a.active {
background-color: #4CAF50;
color: white;
}
.sidebar a:hover:not(.active) {
background-color: #555;
color: white;
}
div.content {
margin-left: 200px;
padding: 1px 16px;
height: 1000px;
}
/* 700px 이하일때 */
@media screen and (max-width: 700px) {
.sidebar {
width: 100%;
height: auto;
position: relative;
}
.sidebar a {float: left;}
div.content {margin-left: 0;}
}
/* 400px 이하일때 */
@media screen and (max-width: 400px) {
.sidebar a {
text-align: center;
float: none;
}
}
</style>
</head>
<body>
<div class="sidebar">
<a class="active" href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
</div>
<div class="content">
<h2>Responsive Sidebar Example</h2>
<p>This example use media queries to transform the sidebar to a top navigation bar when the screen size is 700px or less.</p>
<p>We have also added a media query for screens that are 400px or less, which will vertically stack and center the navigation links.</p>
<h3>Resize the browser window to see the effect.</h3>
</div>
</body>
</html>
5. Css013_RWD7_Form.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Responsive Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="CSS/RWD7.css" rel="stylesheet" type="text/css">
</head>
<!-- form 또한 reponsive 하게 작성 가능 -->
<body>
<h2>Responsive Form</h2>
<p>브라우저를 늘렸다 줄였다 해보기</p>
<!-- TODO : class 설정 -->
<div class="container">
<form action="https://www.w3schools.com/action_page.php">
<div class="row">
<div class="col-3">
<label for="fname">First Name</label>
</div>
<div class="col-9">
<input type="text" id="fname" name="firstname" placeholder="Your name..">
</div>
</div>
<div class="row">
<div class="col-3">
<label for="lname">Last Name</label>
</div>
<div class="col-9">
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</div>
</div>
<div class="row">
<div class="col-3">
<label for="country">Country</label>
</div>
<div class="col-9">
<select id="country" name="country">
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
</div>
</div>
<div class="row">
<div class="col-3">
<label for="subject">Subject</label>
</div>
<div class="col-9">
<textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</div>
</body>
</html>
** RWD7.css
* {
box-sizing: border-box;
}
.container {
padding: 20px;
background-color: #F2F2F2;
border-radius: 5px;
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #CCC;
}
label {
display: inline-block;
padding: 12px 12px 12px 0;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
float: right;
width: 100%;
margin-top: 4px;
}
input[type=submit]:hover {
background-color: #4CA049;
}
.row::after {
content: "";
display: block;
clear: both;
}
[class*="col-"] {
width: 100%;
}
/* 600px 이상인 경우 */
@media (min-width: 600px) {
[class*="col-"] {
float: left;
margin-top: 6px;
}
input[type=submit] {
width: auto;
}
.col-1 {width: 8.33%; } /* 1칸 짜리 폭 */
.col-2 {width: 16.66%; } /* 2칸 짜리 폭 */
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
6. node.js 설치
: 구글에 node js 검색 > Node.js 홈페이지 들어가기
> 안정적, 신뢰도 높은 버전으로 다운로드 받기
> 다운 받은 실행파일 실행하여 설치 완료하기
7. 확장프로그램 다운로드 - Code Runner
: Extensions 클릭 > code runner 검색 > Install 클릭
8. Script 언어란?
: 프로그래밍 언어의 한 종류,
기존에 이미 존재하는 소프트웨어(애플리케이션)를 제어하기 위한 용도로 쓰이는 언어,
인터프리터 방식을 사용하는 것일뿐 인터프리터 언어가 아님
9. ECMA262 (ECMAScript)
: JavaScript가 나중에 ECMA262 표준으로 정착됨.
10. OUTPUT 기본 설정이 기존 컴파일 자료 남아 있음 > 컴파일 하기 전에 OUTPUT 창을 깨끗이 Clear 될 수 있게 설정
: 단축키 Ctrl + ,(콤마)를 누르면 Settings 창이 뜸 > code runner 검색 > Code-runner: Clear Previous Ouput 체크
11. 01_HelloJavaScipt.js
console.log("Hello JavaScipt")
console.log("자바 스크립트")
console.log(100)
console.log('hello' + 'javascript')
console.log(true)
// 표현식 expresson
// 결과가 '값'이 나오는 문장
// 한개 이상의 표현식이 모여 문장(statement)
// 모든 표현식은 문장이 될수 있다
// (일반적으로) 문장의 끝은 세미콜론 붙인다
// 안붙여도 되지만 관례적으로 붙인다
// 한줄에 여러 문장을 적을 경우, 반드시 세미콜론으로 구분해야 한다
// 마지막 문장은 세미콜론을 붙이지 않아도 문제 안됨.
// 마지막 문장의 결과(값) 가 리턴됩니다
// ex : true; 26; 1001
// --> 결과 1001
// 조건문(if), 반복문(for) 도 문장입니다.
// 이 경우 마지막 } 뒤에 세미콜론을 붙이지 않습니다.
// 표현식이 모여서 문장을 만들고
// 문장들이 모여서 프로그램을 만듭니다.
[추가] 표현식은 결과가 값이 나오는 문장, TERMINAL에서 확인하기
12. 02_keyword_reserved.js
var a = 10 // 변수 a 선언하고 정수값 10 대입
// 키워드 (Keywords)
// 자바스크립트에서 특정한 목적을 위해 사용되는 단어
// 이러한 키워드 들은 예약어(?) 로 이미 지정되어 있음
// ex) var 키워드 : 변수 선언
// 예약어 Reserved Word
// 예약어는 프로그래머가 함부로 변수명, 함수명 등으로 사용할수 없다
// 에러 상황들
//var return = '변수명'; // 예약어 return
// function for() {} // 예약어 for
// Reserved keywords
// 이미 특정한 목적을 위해 사용하기 때문에
// 사용할 수 없는 에약어
// JavaScript 의 키워드들은?
// ※ 키워드들은 Runtime 환경에 따라 다르다
// 참조 https://www.w3schools.com/js/js_reserved.asp
// Future Reserved keywords
// 앞으로 특정한 목적을 위해 사용할 가능성
// https://webplatform.github.io/docs/javascript/future_reserved_words/
// 사용할수 없게 해놓았다.
13. 03_identifiers.js
// 식별자 : identifier
// 코드내의 변수, 함수, 혹은 속성을 식별하는 문자열
// 대소문자 구분!
// 유니코드문자(한글도 가능), $, _, 숫자 사용 가능
// 숫자로 시작하면 안됨
// 예약어 불가, 공백불가
// 작명하는 것은 결코 쉬운 일은 아니다.
// 의미없는 이름 사용하지 말고, 역할에 맞는 적절한 이름을 짓도록 노력해야 한다.
var name = 'Mark'; // 변수 name (식별자)
function hello() {} // 함수 hello (식별자)
var person = {name: 'mark', age: 37} // 변수 person (식별자)
// 다음 두 개 변수는 다른 변수다 (식별자는 대소문자를 구분한다)
var myName = 'Mark';
var myname = 'Mark';
var name1;
var $name;
var _name; // 언더바(_)는 가능한데 하이푼(-)은 불가..!!
//var -name;
var 이름; // 한글도 가능은 하지만 비추..!!
// 유효한 자바스크립트 식별자인지 확인하는 사이트
// https://mothereff.in/js-variables
console.log("\n프로그램 종료\n\n\n\n\n\n\n\n")
14. 04_comment.js
// 주석 : comment
// 소스코드에서 프로그램에 영향을 주지않고 무시되는 부분
// 소스코드 이해를 위해 돕는 부분
// 한줄 주석
/* 블럭 주석, 여러줄 주석
*/
15. 05_변수상수.js
// var, let, const
// var를 사용한 변수 선언
var a = 100;
console.log('a=', a)
a = 200;
console.log('a=', a)
var a = 500; // 중복 선언 가능!
console.log('a=', a)
// ES6 부터 let, const 로 변수 상수 지정.
let value = 177; // 변수 value 선언
console.log('value=', value);
value = 555;
console.log('value=', value);
// 에러 : SyntaxError: Identifier 'value' has already been declared
// 중복선언 불가! 동일 이름 변수 let으로 선언 불가
//let value = 277;
// 상수 선언
const b = 1;
console.log("b=",b)
// 오류 : TypeError: Assignment to constant variable.
//b = 2;
// var 는 오늘날 JS 환경에서는 그닥 권장하지 않음
// var 와 let
// IE9, IE10 와 같은 구형 브라우저에서는
// let, const 를 사용 못함.
// 개발 단계에서는 '바벨' 등을 사용하여
// 우리가 개발한 코드가 구형 브라우저 에서동 동작케 함.
let c; // 초기화를 따로 해도 가능.
c = 100;
// ` : back tick
console.log(`c = ${c}`); // Template Literal (ES6 <= )
// 데이터 타입들
let value2 = 100; // number 타입
console.log(value2, typeof value2); // typeof 연산자 : 변수의 타입
console.log(value2, typeof(value2));
// JS 는 대입되는 값에 따라 '타입' 바뀜.
value2 = 'hello'; // String
console.log(value2, typeof value2);
value2 = "Hello"; // ' ~ ', " ~ " 둘 다 가능
16. 06_변수scope.js
// 변수의 유효범위
// scope
// const, let 의 유효범위
// ==> Block Scope
// { ... }
// 블럭
{
const name = 'Mark' // 블럭 안에서만 사용 가능
console.log(`name = ${name}`)
}
// 에러 : ReferenceError: name is not defined
// 블럭 밖에서 사용하려 하면 에러!
//console.log(`name = ${name}`)
{
// 에러 : ReferenceError: Cannot access 'name2' before initialization
//console.log('name2 = ', name2)
const name2 = 'Mark'
}
{
// 이 블록 안의 예시를 통해
// 변수의 유효범위는 Block Scope라는 것을 알 수 있음..!!
console.log('value1 = ', value1); // 에러는 아니다, undefined이 나올뿐
var value1 = 200;
// 에러 : ReferenceError: value2 is not defined
// 선언된 적이 없다는 에러 발생..!!
//console.log('value2 = ', value2);
}
// Hoisting
// https://developer.mozilla.org/ko/docs/Glossary/Hoisting
// 이러한 현상을 hoisting 이라 하는데
// hoisting 현상은 함수에서만 발생하는게 아니다.
// hoising
// 아래에 있는 선언을(만) 끌어올린다.
// hoising 때문에 동작의 오류처럼 보이는 증상 겪게 됨
// hoising 현상은 처음부터 있었으나
// 용어 자체는 ES2015 및 그 이전에는 사용되지 않음
{
// nick is not defined 에러였으나
// 59번째 줄 var nick = '아이언맨';를 추가하면
// undefined으로 출력됨
console.log(`nick=${nick}`); // 2. 가 hoisting 됨
// 자바 스크립트에서는 선언문 없이 변수 선언이 가능함..!!
nick = 'Mighty'; // 1.
console.log(`nick=${nick}`); // 1.
var nick = '아이언맨'; // 2.
// 1. nick 과 2. nick 은 변수 scope 가 다르다
}
age = 6;
age++;
console.log("1. age=", age);
{
console.log(`2. age = ${age}`) // 블록 바깥쪽 scope 의 변수 사용 가능.
age = 30
console.log(`3. age = ${age}`)
//let age; // var age;일때는 동작했으나,
// let 은 hoisting 이 발생 안한다.
}
console.log(`4. age = ${age}`)
17. 07_datatype.js
// 자료형 : data type
// https://developer.mozilla.org/ko/docs/Web/JavaSCript/Data_structures
// 동적타이핑 (dynamic type)
// 변수는 고정타입이 없다
// runtime 에 개발자가 모르는 어떤 타입의 값이
// 들어올수 있다 주의!
// 데이터 타입
// 1.기본타입 (primitive)
// -- boolean
// -- null
// -- undefined
// -- number
// -- string
// -- symbol (ES6 에 추가)
//
// 2. 객체 (object)
// ..
// ---------------------------------------------------------
// boolean 타입
// true / false
{
const isTrue = true;
const ifFalse = false;
console.log(`isTrue = ${isTrue}`, typeof isTrue)
console.log(`ifFalse = ${ifFalse}`, typeof ifFalse)
if(isTrue) {
console.log(isTrue, '참입니다.');
} else {
console.log(isTrue, '거짓입니다.');
}
// 객체로 생성 가능!
// 가능은 하지만 비추..!!
const a = new Boolean(false); // false 값을 갖는 Boolean 객체
console.log('a = ', a, typeof a);
if(a) { // <- new 를 사용하여 생성하면 조건식에서 '참'으로 판정된다..!!
console.log(a, '참입니다.');
} else {
console.log(a, '거짓입니다.');
}
// new 를 사용하지 않고 boolean 만들기
const b = Boolean(false); // Boolean() 함수
console.log('b =', b, typeof b);
if(b) {
console.log(b, '참입니다.');
} else {
console.log(b, '거짓입니다.');
}
}
// ---------------------------------------------------------
// null
// 값이 없는 object
console.log('\n<null>');
{
const a = null;
console.log('a =', a, typeof a); // null 은 object 타입
}
// ---------------------------------------------------------
// undefined
// 아무 값도 대입 안된 상태
{
let b; // 아무 값도 대입 안된 상태, undifined
console.log('b =', b, typeof b);
let a = 10;
a = undefined; // 다시 undefined 로 대입 가능
console.log('a =', a, typeof a);
a = null; b = undefined;
if(a == b) { // == 값이 같은지만 비교
console.log('== 같습니다');
} else {
console.log('== 다릅니다');
}
if(a === b) { // === 값 뿐만 아니라 type 까지 비교
console.log('=== 같습니다');
} else {
console.log('=== 다릅니다');
}
// == 값만 비교, === 타입까지 비교
// 가급적 JS 프로그래밍에 작성시 == 보단 === 추천
// != 보단 !== 추천
}
// ---------------------------------------------------------
// number
console.log('\n<number>')
{
// 실수이든 정수이든 모두 number 타입
const a = 37;
console.log('a =', a, typeof a);
const b = 3.14;
console.log('b =', b, typeof b);
const c = NaN; // NaN(Not a Number)
console.log('c =', c, typeof c);
let d = Number(123);
console.log('d =', d, typeof d); // number
d = Number('123'); // number 로 형변환 됨!
console.log('d =', d, typeof d); // number
d = Number('Mark');
console.log('d =', d, typeof d); // NaN
d = parseInt('123'); // 이 또한 number 로 형변환
console.log('d =', d, typeof d); // number
d = parseInt('Alice');
console.log('d =', d, typeof d); // NaN
// 자바는 exception으로 프로그램이 죽는데
// 자바 스크립트는 프로그램이 죽지 않고 NaN(Not a Number)이 출력됨
d = parseFloat('3.14'); // number 로 형변환
d *= 2;
console.log('d = ', d, typeof d);
d = parseInt('3.14'); // '3.14' -> 3 으로 형변환
console.log('d =', d, typeof d);
d = parseFloat('300');
console.log('d =', d, typeof d); // 300
num1 = 100; num2 = '100';
if(num1 == num2) { // == 값만 비교
console.log('${num1} == ${num2} 같다');
} else {
console.log('${num1} == ${num2} 다르다');
}
num1 = 100; num2 = '100';
if(num1 === num2) { // === 값과 타입을 비교
console.log('${num1} === ${num2} 같다');
} else {
console.log('${num1} === ${num2} 다르다');
}
}
// ---------------------------------------------------------
// string(문자열)
// ' ~ ', " ~ " 둘 다 가능..!!
console.log('\n<string>')
{
let a = 'Mark'
console.log('a =', a, typeof a)
a = "Mark" // 쌍따옴표
console.log('a =', a, typeof a)
// She's gone
// 이건 무조건 쌍따옴표
a = "She's gone";
console.log('a =', a, typeof a)
// He says "Hello"
// 이건 무조건 홑따옴표
a = 'He says "Hello"';
console.log('a =', a, typeof a)
// He says "I'm fine"
// 이런 경우는 escape 문자를 사용하면 됨
a = "He says \"I'm fine\""
console.log('a =', a, typeof a)
// + 문자열 연산
a = "Mark"
let b = a + " Hamill";
console.log('b =', b, typeof b)
// 파이썬에서는 문자열 곱하기가 되나
// 자바스크립트는 NaN(Not a Number)로 출력
// 문자열 곱하기란? MarkMark 로 원하는 만큼 문자열이 출력됨
console.log(a * 2)
// 문자열 비교 연산 가능!
// 코드순 비교..!!
console.log("a" > "b")
console.log("a" < "b")
console.log("abc" < "abd")
console.log("AAaa" > "AaAa") // false, 대문자 < 소문자
}
//-------------------------------------------------
// symbol
// ES6 부터 출현
// https://developer.mozilla.org/ko/docs/Glossary/Symbol
// '고유'한 값을 만들어낼때 사용
console.log('\n<symbol>')
{
// 에러 : TypeError: Symbol is not a constructor
//const a = new Symbol();
const a = Symbol(); // new 사용하면 안됨
const b = Symbol(37); // Symbol(매개변수)
const c = Symbol('Mark');
const d = Symbol('Mark'); // c, d 는 같은 것이 아니다
// '고유'한 Sysbol 객체로 만들어 진다
console.log('a =', a, typeof a);
console.log('b =', b, typeof b);
console.log('c =', c, typeof c);
console.log('d =', d, typeof d);
console.log(c == d)
console.log(c === d)
// 일반 문자열
e = 'Mark', f = 'Mark'
console.log(e == f)
console.log(e === f)
}
console.log("\n프로그램종료\n")
18. Javascript는 객체 지향 언어 아님, 함수가 객체 역할할뿐..!!
19. Javascript는 프로토 타입 기반 객체 생성을 지원하는 동적 스크립트 언어이다.
20. 자바스크립트(JavaScript)는 모질라(Mozilla)에서 확인하면 된다
: https://developer.mozilla.org/ko/docs/Web/JavaScript
21. 08_조건문.js
// if ~ else
// if ~ else if ~ else ...
// JAVA, C 언어와 구조 동일
a = 100
if(a + 1 > 100) { // 참 판정
// 에러 : Cannot access 'a' before initialization
// 13번째 줄에서 a 선언할때 var로 선언했다면 100의 값이 출력되었을 것임
// 왜냐하면 let은 hoisting 이 안되기 때문에...!!
//console.log('if 안의 a 값은', a);
let a = 10;
console.log('if 안의 a 값은', a); // 출력 값은 10
}
// 조건식에서 참 거짓 판정
// Falsy 로 평가될때! (거짓으로 판정된다는 의미)
// false, 0, '', null, undefined, NaN <-- 'Falsy 한 값'이라 한다
// Truthy 로 평가될때! (참으로 판정된다는 의미)
// true, 37, 'Mark', {}, [] <-- 'Truthy 한 값' 이라 한다
// 파이썬과 달리 자바스크립트는 {}, []을 참으로 받아들임...!!!!
// 자바스크립트의 함수는 리턴타입 명시 안해도 됨..!!
function print(data) {
if(data) { // 참(Truthy) 거짓(Falsy) 판정
console.log(data, typeof data, '-- Truthy');
} else {
console.log(data, typeof data, '-- Falsy')
}
}
// 자바스크립트는 매개변수가 생성자 역할을 함..!!
print(true)
print(false)
print(0) // F
print(-1) // T
print('hello') // T
print('') // F
print([10, 20, 30]) // T
print([]) // T, [중요] 파이썬과 반대로 출력
print({'name' : 'John', 'age' : 32}) // T
print({}) // T, [중요] 파이썬과 반대로 출력
print(null) // F
print(undefined) // F
print(NaN) // F
console.log(100/0) // Infinity 출력
print(100/0) // T
print() // 호출시 전달인자 없으면 undefined 값으로 동작함
// 파이썬과 자바에서는 이런 경우는 짤업이 에러..!
console.log()
// Falsy 값에 ! 결과 -> true (boolean)
console.log(!undefined)
console.log(!null)
console.log(!0)
console.log(!"")
console.log(!NaN)
// Truthy 값에 ! 결과 -> false (boolean)
console.log(!3)
console.log(!"Hello")
console.log(!" ")
console.log(![10, 20, 30])
console.log(![])
console.log(!{})
// Truthy, Falsy 판정 결과 -> boolean
// 1. 삼항연산자 사용
let value = {'a' : 100}
let isTrue = value ? true : false;
console.log('isTrue =', isTrue, typeof isTrue)
// 2. !! 사용하면 가능
ifTrue = !!value;
console.log('isTrue =', isTrue, typeof isTrue)
console.log()
// 함수 정의할 때 매개변수 체크 필요..!!
function printName(person) {
// 매개변수 체크 null check
//if(person === undefined || person === null) {return;}
if(!person) {return;} // 간단하게 해결..!!
console.log('이름은', person.name)
}
let myBrother = {name : "John"}
printName(myBrother)
// 에러 : TypeError: Cannot read property 'name' of undefined
// 함수 내에 매개변수 not null을 체크하여 에러나지 않도록 코딩 가능
printName()
22. 09_SCE.js
// 논리연산자
// && and 연산자
// || or 연산자
// ! not 연산자
console.log(true && true)
console.log(true && false)
console.log()
let a = 100
console.log(a > 10 || a + 10 < 10)
console.log(a < 10 || a + 10 < 10)
console.log()
console.log(a > 10 && a + 10 < 10)
console.log(a < 10 && a + 10 < 10)
console.log()
// 논리연산자를 이용한 조건문 실행
// Short Circuit Evaluation
// 표현식1 && 표현식2
// 표현식1 이 Falsy 이면 && 의 결과값은 표현식1
// 표현식1 이 Truthy 이면 && 의 결과값은 표현식2
// 표현식1 || 표현식2
// 표현식1 이 Falsy 이면 || 의 결과값은 표현식2
// 표현식1 이 Truthy 이면 || 의 결과값은 표현식1
// 즉, 왼쪽 문자열이 출력되느냐, 오른쪽 문자열이 출력되느냐 결정하는 것..!!
// OR 연산자인 경우,
// 왼쪽 결과값이 참이면 왼쪽값을 출력
console.log("Hello" || "world")
// OR 연산자인 경우,
// 왼쪽값이 거짓이고 오른쪽값이 출력
console.log(0 || "world")
console.log()
// AND 연산자,
// 왼쪽값이 참일경우 오른쪽값이 출력
console.log(5 && 100)
console.log(5 && 0)
console.log()
// AND 연산자,
// 왼쪽 값이 거짓이면 왼쪽값이 출력
console.log(null && 'hello')
console.log(100 - 100 && [10, 20, 30])
console.log()
let n = 15;
(n % 5 === 0) && console.log('5의 배수입니다.')
n = 7;
(n % 5 === 0) && console.log('5의 배수가 아닙니다.')
23. 10_함수1.js
// function 함수이름 (매개변수 ... )
function add (a, b) {
return a + b;
}
var sum = add(1, 2);
console.log("sum =", sum);
// JS 에서 '함수(function) 도 데이터 다!
console.log(typeof add) ;
console.log(add);
// 따라서,
// 함수를 변수에 대입할 수도 있고
// 함수를 매개변수로 넘겨줄 수도 있고
// 함수를 리턴할 수도 있다.
// -----------------------------------------------------
// JS는 함수 정의시 아래와 같은 표현을 더 선호함.
// 이름 없는 함수 사용..!!
var sub = function(a, b) {
return a - b;
}
console.log(sub(10, 3))
let mul = function(a, b) {return a * b;}
console.log(mul(4, 5))
let bbb = mul; // 이제 bbb 도 함수다!!!
console.log(bbb(100, 2))
var arr = [add, sub, mul];
console.log(arr[0](10, 20))
console.log(arr[1](10, 20))
console.log(arr[2](10, 20))
24. 11_화살표함수.js
// 화살표 함수 (ES6 도입)
// 함수를 정의하는 또 다른 방법
// 화살표 함수
// const 나 let 으로 시작
const add = (a, b) => {
return a + b;
}
let sum = add(1, 2)
console.log(`sum = ${sum}`)
const hello = name => {
console.log(`Hello, ${name}!`);
}
hello('헐크');
// return 값이 있는 화살표 함수는
// 더 간략하게 정의 가능
const add2 = (a, b) => a + b;
sum = add2(10, 20);
console.log(`sum = ${sum}`)
25. 12_배열.js
// 배열 생성 방법
// 방법1 : [ ] 사용
var points = [40, 100, 1, 5, 25, 10];
var fruits = ['Banana', 'Orange', 'Apple', 'Mango']
console.log('points =', points, typeof points)
// 방법2 : new 사용
var cars = new Array("Saab", "Volvo", "BMW"); // 비추..!!
console.log('cars =', cars, typeof cars);
console.log('fruits =', fruits.toString());
// JS 에선 object 의 property 접근 회수를 줄이는 것이 성능에 유리하다..!!
console.log()
for(i = 0; i < cars.length; i++) {
console.log(cars[i])
}
console.log()
var length = cars.length;
for(i = 0; i < length; i++) { // 위의 경우보다 좋은 성능...!!
console.log(cars[i])
}
console.log()
// for ~ in : 객체(Object) 에 대해 사용, property
for(x in cars) { // value 가 아닌 index 가 나옴.
console.log('x =', x, cars[x])
}
console.log()
// for ~ of : ES6부터 사용, iterable 한 객체에 대해 사용
for(x of cars) {
console.log('x =', x)
}
console.log()
// 배열.forEach(함수)
// 배열 원소 하나 하나 뽑아내면서 함수 호출
var myFunction = function(value) {
console.log(value);
}
cars.forEach(myFunction);
// 배열원소 추가
console.log()
fruits[fruits.length] = 'Menlon'
console.log(fruits)
fruits.push('Lemon');
console.log(fruits);
console.log()
// 주어진 변수가 배열인지 아닌지 판단
// typeof 만으로는 알 수 없다
// 1. isArray() : ES5.1 부터 지원
console.log(Array.isArray(fruits));
// 2. 구 브라우저에서 판단하려면 함수 만들어서 운영
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
console.log(isArray(fruits));
// 3. instanceof 연산자
console.log(fruits instanceof Array);
// ------------------------------------------------------------
// join()
console.log(cars.join("**"))
console.log([2020, 5, 7,].join("/"))
console.log()
// push() : 배열끝 원소 추가
// pop() : 배열 끝 원소 추출
// shift() : 배열 첫 원소 추출
// unshift() : 배열앞에 원소 추가, 새로운 length 리턴
console.log(fruits.toString());
console.log(fruits.pop());
console.log(fruits.toString())
console.log(fruits.shift());
console.log(fruits.toString());
console.log(fruits.unshift('Grape')); // 배열 앞에 추가, 새 lenth 리턴
console.log(fruits.toString());
console.log()
// splicing
// 첫번째 매개변수 : 삽입될 데이터 위치
// 두번째 매개변수 : 삭제될 데이터 개수
// 세번째 이후 .. : 삽입될 데이터 들..
fruits.splice(2, 0, "Kiwi", "Jadu");
console.log(fruits.toString());
fruits.splice(1, 3, "Durian");
console.log(fruits.toString());
// concat()
// 원본 변화시키지 않아요..!!
console.log(fruits.concat(['Lemon', 'Banana']));
console.log(fruits.toString());
fruits = fruits.concat(['Lemon', 'Banana']); // 원본 변화
console.log(fruits.toString());
// 배열 데이터 중간에 삭제하려면..?
fruits.splice(1, 3);
console.log(fruits.toString());
// slice()
// 배열의 일부분만 추출, 원본에는 영향을 안줌
console.log(fruits.slice(1, 3)) // 1부터 3전까지
console.log(fruits.slice(1)) // 1부터 끝까지
// 배열의 원소는 어떠한 타입이어도 가능
var arr = [10, 3.14, 'hello', null, undefined, function(a, b){return a + b;}]
// 배열의 원소가 배열일 수도 있다!! -> 다차원 배열
arr = [[10, 20], [30, 40], [50, 60]]
// arr.length --> 3
// TODO
// for문 사용해서 출력
console.log('\n내가 만든거')
for(x of arr) {
console.log(x.toString())
}
console.log('\n쌤이 만든거')
for(i = 0; i < arr.length; i++) {
console.log(arr[i].toString())
}
26. 13_문자열.js
var str1, str2, str3;
str1 = "John"
str2 = new String("John"); // 비추하는 방법
console.log(str1, typeof str1)
console.log(str2.toString(), typeof str2)
console.log(str1 == str2)
console.log(str1 === str2)
console.log(str1.length); // 문자의 개수
str2 = "Hello Java Web FrameWork";
console.log(str2)
// 문자열 리터럴 중간을 끊어서 작성할 경우...
str2 = "Hello Java W\
eb FrameWork";
console.log(str2)
// indexOf(), lastIndexOf(), search() : 문자열 안에서 문자열 찾기
// 찾은 위치 인덱스 리턴, 못찾으면 -1 리턴
console.log("문자열 검색\nindexOf(), lastIndexOf(), search()");
str1 = "Please locate where 'locate' occurs!";
console.log(str1.indexOf("locate")) // 7번째 발견
console.log(str1.lastIndexOf("locate")) // 21번째 발견
console.log(str1.indexOf("John")) // 못 찾으면 -1 리턴
console.log(str1.indexOf("locate", 10)) // 10번째부터 검색 시작
console.log(str1.indexOf("locate", 25)) // 못 찾으면 -1 리턴
// search() : 문자열 안에서 문자열 찾기
console.log(str1.search("locate")) // 7
// search() vs indexOf() : 둘은 다르다!
// search() : 두번째 매개변수 없다
// indexOf() : regexp 사용 불가
// 문자열 추출
// slice(start, end)
// substring(start, end)
// substr(start, length)
console.log("문자열 추출\nslice(), substring(), substr()");
str1 = "Apple, Banana, Kiwi";
console.log(str1.slice(7, 13)); // 7부터 13전까지
console.log(str1.slice(-12, -6)); // 음수 인덱싱도 가능..!!
console.log(str1.slice(7)); // 7부터 끝까지
console.log(str1.slice(-12)); // -12부터 끝까지
console.log(str1.substring(7, 13)); // slice()와 유사하나 음수 인덱싱 지원 안함.
console.log(str1.substring(7)); // 7부터 끝까지
console.log(str1.substr(7, 6)); // 7부터 6글자
console.log(str1.substr(7)); // 7부터 끝까지
// 문자열 치환
// replace() : 치환한 결과 문자열 리턴, 정규표현식 사용 가능
// 기본적으로 첫번째 '매칭된 문자열 만 치환
console.log("문자열 치환 replace()");
str1 = "Please visit Japan!";
console.log(str1.replace("Japan", "Korea")); // 원본 str1 변경 안한다..!!
console.log(str1.replace("JAPAN", "Korea"));
console.log(str1.replace(/JAPAN/i, "Korea")); // 정규표현식 대소문자 구분없이 치환
str2 = "Please visit Japan! Go Japan";
console.log(str2.replace("Japan", "Korea")); // 기본적으로 첫번째만 치환됨.
console.log(str2.replace(/Japan/g, "Korea")); // 정규표현식, global match
str3 = "Hello World!";
console.log(str3.toUpperCase());
console.log(str3.toLowerCase());
str1 = 'Hello'; str2 = "World";
console.log(str1 + " " + str2);
console.log(str1.concat(" ", str2));
// trim() : 좌우 공백 제거
str1 = " Hello World! "
console.log(`str1 = [${str1}]`)
str2 = str1.trim();
console.log(`str1 = [${str2}]`);
// split() : String -> array
str3 = '2020-05-07';
console.log(str3.split('-'));
console.log('\n\n\n\n프로그램 종료')
'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글
2020.05.11 (0) | 2020.05.11 |
---|---|
2020.05.08 (0) | 2020.05.08 |
2020.05.06 (0) | 2020.05.06 |
[2020.04.21] 구글 스토어 앱 출시 완료! (0) | 2020.05.02 |
2020.04.29 (0) | 2020.04.29 |